Home > Software design >  Adding Characters to an Empty String in Python
Adding Characters to an Empty String in Python

Time:07-20

I am attempting to have my program iterate over a user-inputted string and print it again, with a "u" in place of every uppercase letter, an "l" in place of every lowercase letter, and a "-" in place of any other character. This is what I have written:

txt = input()
modified_txt = ""

for char in txt:
    if char.isupper():
        modified_txt   "u"
    elif char.islower():
        modified_txt   "l"
    else:
        modified_txt   "-"

print(modified_txt)

For some reason, my output is a blank line, as though the variable "modified_txt" was never affected by the for loop. I'm sure there's a straightforward reason why this is the case but I'm at a loss.

CodePudding user response:

maybe you need add characters before =

txt = input()
modified_txt = ""

for char in txt:
    if char.isupper():
        modified_txt  = "u"
    elif char.islower():
        modified_txt  = "l"
    else:
        modified_txt  = "-"

print(modified_txt)

CodePudding user response:

A string is an immutable data type. So is not an inplace operation for a string.

You need to reassign your variable with the new values. So change the lines:

modified_txt   SOMETHING

to

modified_txt = modified_txt   SOMETHING

or as Matiiss suggested to:

modified_txt  = SOMETHING
  • Related