简体   繁体   中英

Adding Characters to an Empty String in Python

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM