Home > Software engineering >  Loop through a string with variable and replace an uppercase it with # in Python
Loop through a string with variable and replace an uppercase it with # in Python

Time:06-14

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.

CodePudding user response:

Use list comprehension with join:

In [4]: ''.join([i if not i.isupper() else '#' for i in string])
Out[4]: 'h#w #re y#u?'

CodePudding user response:

You just want to put the result again in string see below

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

CodePudding user response:

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.

CodePudding user response:

This should do the trick!

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

I'm a novice as well! But from what I learned: when doing loops or if statements, you want to specify the value you are changing as I did in line 4 with: string = string.replace(x,'#') If not the change will not take effect!

Example:
my_list = [1,2,3,4]
for x in my_list:
    my_list[x-1] = x   1
print(my_list)

This is a poor example coding wise but it exemplifies the concept. If you don't address the variable it wont have any effect on it!

Hope this helps!

  • Related