Search code examples
pythonloopsif-statementuppercaseiterable

Loop through a string with variable and replace an uppercase it with # in Python


I want to loop through a string and when it finds an uppercase letter, I want to replace it with #. Like this:

string = "hOw Are yOu?"
for x in string:
  if x.isupper():
    string.replace(x, "#")
    print(string)
  else:
    print(string)

However, its not working as intended and is instead outputting the same string. Do tell me if there is a way to fix this or if you'd suggest another way.


Solution

  • Strings are immutable in Python. string.replace(x, "#") must thus be string = string.replace(x, "#") to have an effect on the string.

    Note that currently your code has quadratic complexity as each replace operation has to loop over the entire string in linear time. A more efficient approach would be to perform the replacements yourself, as you're already looping over every character:

    string = "".join(["#" if c.isupper() else c for c in "hOw Are yOu?"])
    

    it would be even more concise (and possibly faster) to use a very simple RegEx for this:

    import re
    string = re.sub("[A-Z]", "#", "hOw Are yOu?")
    

    this will fail for non-ASCII alphabets however; you'd have to use unicode properties & regex there.