Why doesn't calling a Python string method do anything unless you assign its output?

前端 未结 2 2187
鱼传尺愫
鱼传尺愫 2020-11-21 04:24

I try to do a simple string replacement, but I don\'t know why it doesn\'t seem to work:

X = \"hello world\"
X.rep         


        
2条回答
  •  悲&欢浪女
    2020-11-21 04:41

    All string functions as lower, upper, strip are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable, it will fail.

    x = 'hello'
    x[0] = 'i' #'str' object does not support item assignment
    

    There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them

提交回复
热议问题