1

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.

2
  • 3
    strings are immutable, meaning you can't modify them like this, you can tho use += to reassign and add a character, so modified_txt += "u" and so on (it's equivalent to modified_txt = modified_txt + "u") Commented Jul 20, 2022 at 7:17
  • Strings in python are unmutable, besides, need to reassign the variable Commented Jul 20, 2022 at 7:17

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Didn't you mean " = characters after +"?
2

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

3 Comments

I didn't exactly suggest it... it's just something that one should really use instead of that extended thing (which can be used to explain what += does but not really used because, well, there's a shorter option that everyone uses)
@Matiiss I know people (such as myself) who prefer the first method. Because I think the first method is more readable. But you're absolutely right. One should know.
+ shouldn't be in-place operation even for mutable types. That's what += is for. a + b on its own in a line of code pretty much never makes sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.