Python readline() 没有读取单个 space 的行
Python readline() is not reading a line with single space
我正在使用 readline() 读取文本文件。我的文件包含以下内容,第二行带有 space:
!
"
#
$
%
&
当我使用-
打印读取值时
print("'%s'\n" % iso5_char)
它打印-
'!'
''
'"'
'#'
'$'
'%'
'&'
似乎 readline() 没有读取第二行的 'space'。
我是第一次使用 python。我安装了 python-3.5。我在这里做错了什么?为什么 space 没有被读取?
更新:
我正在阅读的文件的屏幕截图:
根据对原始问题的评论,您使用以下表达式明确删除了 space:
iso5_char.rstrip()
来自 rstrip
的文档:
Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.
在此上下文中,"whitespace" 指的是 space、制表符、换行符、回车符 returns、换页符和垂直制表符。
如果您使用 rstrip
的目的只是去除尾随的换行符,您可以将换行符传递给 rstrip
命令:
iso5_char.rstrip('\n')
或者,您可以简单地砍掉最后一个字符,因为可以安全地假设它是换行符:
iso5_char[:-1]
我正在使用 readline() 读取文本文件。我的文件包含以下内容,第二行带有 space:
!
"
#
$
%
&
当我使用-
打印读取值时print("'%s'\n" % iso5_char)
它打印-
'!'
''
'"'
'#'
'$'
'%'
'&'
似乎 readline() 没有读取第二行的 'space'。
我是第一次使用 python。我安装了 python-3.5。我在这里做错了什么?为什么 space 没有被读取?
更新: 我正在阅读的文件的屏幕截图:
根据对原始问题的评论,您使用以下表达式明确删除了 space:
iso5_char.rstrip()
来自 rstrip
的文档:
Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.
在此上下文中,"whitespace" 指的是 space、制表符、换行符、回车符 returns、换页符和垂直制表符。
如果您使用 rstrip
的目的只是去除尾随的换行符,您可以将换行符传递给 rstrip
命令:
iso5_char.rstrip('\n')
或者,您可以简单地砍掉最后一个字符,因为可以安全地假设它是换行符:
iso5_char[:-1]