繁体   English   中英

如何在Python中使用line.rstrip()?

[英]How use line.rstrip() in Python?

我正在尝试使用Python读取文件。 这是我的文件test.txt:

Hello World
My name is Will
What's your name?

这是我的python代码:

fhand = open('test.txt')
for line in fhand:
    line.rstrip()
    print line

无论我是否使用line.rstrip() ,输出始终如下:

Hello World

My name is Will

What's your name?

如何在没有空行的情况下使用像这样的rstrip()输出?

Hello World
My name is Will
What's your name?

line.rstrip()不会更改旧变量,它会返回旧变量的剥离值,您必须重新分配它才能使更改生效,例如:

line = line.rstrip()

否则,该行不会更改,它使用旧行而不是剥离行。

 line.rstrip()

在这里你得到了剥离的字符串,但你没有存储该值。

替换line.rstrip()line = line.rstrip()

我们来看看演示:

>>> string = "hello    "
>>> string.rstrip()
'hello'
>>> string
'hello    '
>>> string = string.rstrip()
>>> string
'hello'
>>> 

python(和其他语言)中的字符串是不可变的,这意味着一旦创建它们就无法修改,因此line.rstrip()基本上会创建一个带有剥离内容的新字符串实例。

您可以在打印前将变量设置为它:

line = line.rstrip()

其他字符串函数也是如此:例如:strip,lowercase,uppercase等和切片例如:line [1:]

要了解其他类型的行为,请查看: https//en.wikibooks.org/wiki/Python_Programming/Data_Types#Mutable_vs_Immutable_Objects

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM