在python中使用.split()方法

在python中使用.split()方法,python,string,methods,split,newline,Python,String,Methods,Split,Newline,我正在从文本文件中获取输入,并尝试在遇到“\n”字符时拆分文本,但它不会拆分任何内容。我在标签和空格上试过,效果非常好。由于某些原因,它不适用于换行符。这和我拿绳子的方式有关吗?我正在把文件传送到程序中。当我在空闲状态下尝试相同的代码行时,效果很好 t= input("input string : " ) ... tps = t.split('\n') print(tps) 对于在换行符上拆分多行字符串,您通常会使用,它处理不同的换行符约定: >>> 'Test\r\nl

我正在从文本文件中获取输入,并尝试在遇到“\n”字符时拆分文本,但它不会拆分任何内容。我在标签和空格上试过,效果非常好。由于某些原因,它不适用于换行符。这和我拿绳子的方式有关吗?我正在把文件传送到程序中。当我在空闲状态下尝试相同的代码行时,效果很好

t= input("input string : " )
...


tps = t.split('\n')
print(tps)

对于在换行符上拆分多行字符串,您通常会使用,它处理不同的换行符约定:

>>> 'Test\r\nlines\nall mixed\r'.splitlines()
['Test', 'lines', 'all mixed']
请注意,
input()
在任何情况下都只给出第一行;对于多行输入,您可能希望从
sys.stdin
读取:

for line in sys.stdin:
    # handle a line
或读取循环中的行:

while True:
    line = input()

对于在换行符上拆分多行字符串,您通常会使用,它处理不同的换行符约定:

>>> 'Test\r\nlines\nall mixed\r'.splitlines()
['Test', 'lines', 'all mixed']
请注意,
input()
在任何情况下都只给出第一行;对于多行输入,您可能希望从
sys.stdin
读取:

for line in sys.stdin:
    # handle a line
或读取循环中的行:

while True:
    line = input()
input()
只读取一行。您需要在循环中运行它,一次读取一行:

try:
    while True:
        t = input("input string : " )  # Or raw_input for Python 2
        print t.replace('e', 'X')
except EOFError:
    pass
python x.py
的形式运行该示例,它将打印:

input string : try:
input string :     whilX TruX:
input string :         t = raw_input("input string : " )
input string :         print t.rXplacX('X', 'X')
input string : XxcXpt EOFError:
input string :     pass
input string :
input()
只读取一行。您需要在循环中运行它,一次读取一行:

try:
    while True:
        t = input("input string : " )  # Or raw_input for Python 2
        print t.replace('e', 'X')
except EOFError:
    pass
python x.py
的形式运行该示例,它将打印:

input string : try:
input string :     whilX TruX:
input string :         t = raw_input("input string : " )
input string :         print t.rXplacX('X', 'X')
input string : XxcXpt EOFError:
input string :     pass
input string :

文件是在Windows计算机上创建的吗?如果是这样,行结尾可能是
\r\n
文件是在Windows计算机上创建的吗?如果是这样的话,
\r\n
\n
上的行尾很可能仍然会被拆分,但OP会说“它不会拆分任何东西”。@RichieHindle:如果使用
\r
,它不会被拆分。不太可能,我同意,但是仍然。你需要一台时间机器(或者,
\n
上正在工作的MacOS拆分仍然会拆分,但是OP说“它不会拆分任何东西”。@RichieHindle:如果使用
\r
它不会拆分。不可能,我同意,但是仍然。你需要一台时间机器(或者一个正在工作的MacOS真的这就是答案!@GrijeshChauhan:为什么不呢?@MartijnPieters实际上我的问题是OPI在我的程序中有一个循环,但它仍然不起作用。@HarryHarry:我的第一个版本会在它碰到一个空行时完成,这可能是问题所在。请查看我更新的答案。真的这是问题所在吗回答?!!@GrijeshChauhan:为什么不呢?@MartijnPieters实际上我的问题是在我的程序中OPI将它放入一个循环中,但它仍然不起作用。@HarryHarry:我的第一个版本将在它碰到一个空行时完成,这可能是问题所在。请查看我更新的答案。