注意:在文件中,“\ n”用于新行,其长度为1,“\\ n”用于字符串“\ n”,其长度为2。
当我在Line="Some thing\n"
之后给出Line.split()
时,它会给出单词列表[“Some”,“thing”]并跳过\n
它不会给thing\n
。我没有使用它默认执行的strip()
函数。普通的strip()函数用于从行尾跳过\n
。
check.txt:
abc abc abc \\n abc abc abc abc abc abc abc abc abc abc abc abc abc
abc abc abc
我的代码是:
fileread=open("check.txt","r")
for line in fileread:
print("Line:",line , "lenght :",len(line))
words=line.split() #It Skip NewLine by Default
print("Words List in Line:",words)
输出:
Line: abc abc abc \\n abc abc abc abc abc abc abc abc abc abc abc abc abc
lenght : 68
Words List in Line: ['abc', 'abc', 'abc', '\\\\n', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc']
Line:
lenght : 1
Words List in Line: []
Line: abc abc abc
lenght : 12
Words List in Line: ['abc', 'abc', 'abc']
我的问题是,可以拆分功能默认情况下可以从Line中删除特殊字符吗? 为什么行:“\ n”不创建列表[“\ n”]并创建空列表[]
答案 0 :(得分:0)
Split()函数默认情况下拆分所有这些字符。Link
中的描述Representation Description
\n Line Feed
\r Carriage Return
\r\n Carriage Return + Line Feed
\v or \x0b Line Tabulation
\f or \x0c Form Feed
\x1c File Separator
\x1d Group Separator
\x1e Record Separator
\x85 Next Line (C1 Control Code)
\u2028 Line Separator
\u2029 Paragraph Separator
Python代码
>>> data= "dsddddd\ndasdasd\ndasdasdas\nasfsafs\n"
>>> print(data.split())
['dsddddd', 'dasdasd', 'dasdasdas', 'asfsafs']
>>> data="aaaaaaaaaaa aaaaaaaaaaaa aaaaaaaaaa"
>>> print(data.split())
['aaaaaaaaaaa', 'aaaaaaaaaaaa', 'aaaaaaaaaa']
>>> data= "dsddddd\rdasdasd\rdasdasdas\rasfsafs\r"
>>> print(data.split())
['dsddddd', 'dasdasd', 'dasdasdas', 'asfsafs']
>>> data= "dsddddd\u2029dasdasd\u2029dasdasdas\u2029asfsafs\u2029"
>>> print(data.split())
['dsddddd', 'dasdasd', 'dasdasdas', 'asfsafs']
>>>