Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

python - string.upper(<str>) and <str>.upper() won't execute

I have the following bit of code:

def test():
    fragment = ''
    fragment = raw_input('Enter input')
    while fragment not in string.ascii_letters:
        fragment = raw_input('Invalid character entered, try again: ')
    fragment.upper()
    print fragment*3

However when I run it, say for an input value of p, fragment gets printed as 'ppp' - all lower case, i.e. the fragment.upper() line does not run. The same thing happens if I replace that line with string.upper(fragment) (and adding import string at the beginning). Can someone tell me what I'm doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Strings are immutable. So functions like str.upper() will not modify str but return a new string.

>>> name = "xyz"
>>> name.upper()
'XYZ'
>>> print name
xyz  # Notice that it's still in lower case.
>>> name_upper = name.upper()
>>> print name_upper
XYZ

So instead of fragment.upper() in your code, you need to do new_variable = fragment.upper()and then use this new_variable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...