Replace string case using Python for statement

Asked 2 weeks ago, Updated 2 weeks ago, 1 views

In Python, it says that to change the case of a string using the for statement, it should be the code below, but I don't know why it should be specified as new_text = str()!

text = input('English case sentence)\n')
new_text = str()

for c in text:
  if c.islower():
    new_text += c.upper()
    new_text += c.lower()

print (use '\nfor' and if statements to change case\n'+ new_text)
text = input('English case sentence)\n')

for c in text:
  if c.islower():
    text += c.upper()
    text += c.lower()

print (use '\nfor' and if statements to change case\n'+ text)

Why doesn't it come out if I do it like the code below?

python string for

2022-09-20 15:56

1 Answers

It's not that it's not coming out, but something is coming out

Enter a sentence in English case
what the heck

Change case using the for statement and the if statement
what the heckWHAT THE HECK

If you think about it a little bit, it's obvious.
text+='W' is to put 'W' after text.
So if text = 'what the hek' then text + = 'W' will be executed, then what the hekW will appear.
It stuck one by one and ended up being what the hek WHAT THE HECK.

You can't say that something came out and it doesn't come out.
"What I wanted/expected won't come out" You might not know.

Let's think about it a little bit more.
In fact, what we're doing here is we're using the text that the user enters to get new text.
The new text could be named new_text.
Oh, but it doesn't matter from Python's point of view whether it's a number or a letter! That's why new_text = str().
That way, Python doesn't panic when he sees the command new_text+='W' and understands that he needs to put a string at the end of that string.

2022-09-20 15:56

If you have any answers or tips

© 2022 pinfo. All rights reserved.