search

Home  >  Q&A  >  body text

python - 为何print(my)还会输出小写的x,y,z?为何输出的不是字符串?

c=['x','y','z']

for my in c:
    my.capitalize()
    print(my)

在 IDE 中输出:

'X'
x
'Y'
y
'Z'
z

请问,my 不是已经都变成大写的了吗? 为何 print(my) 还会输出小写的 x,y,z

为何输出的不是字符串?

谢谢

大家讲道理大家讲道理2890 days ago638

reply all(4)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:52:30

    my = my.capitalize()Write it like this and it will change. Strings are immutable, a new string can only be created to replace the old one.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 17:52:30

    Because capitalize is pure (escape

    Look at the function signature

    >>> help(str.capitalize)
    Help on method_descriptor:
    
    capitalize(...)
        S.capitalize() -> str
    
        Return a capitalized version of S, i.e. make the first character
        have upper case and the rest lower case.

    It just returns a capitalized version of str without changing the original str

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 17:52:30

    str is an immutable type, str.capitalize will not act on the original string, but will return a new string

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 17:52:30

    print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

    This is Python's print function definition, that is to say, the end parameter is added by default, and its default is 'n', so it will wrap.

    reply
    0
  • Cancelreply