string.upper(< str>)和< str> .upper()不会执行 [英] string.upper(<str>) and <str>.upper() won't execute

查看:115
本文介绍了string.upper(< str>)和< str> .upper()不会执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

但是,当我运行它时,例如对于输入值pfragment被打印为'ppp'-所有小写字母,即fragment.upper()行不运行.如果我用string.upper(fragment)替换该行(并在开始处添加 import string ),也会发生同样的事情.有人可以告诉我我在做什么错吗?

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?

推荐答案

字符串是不可变.因此,像str.upper()这样的函数将不会修改str而是返回一个新字符串.

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

因此,您需要执行new_variable = fragment.upper()而不是代码中的fragment.upper(),然后使用此new_variable.

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

这篇关于string.upper(< str>)和< str> .upper()不会执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆