【问题标题】:Using the .split() method in python在 python 中使用 .split() 方法
【发布时间】:2013-07-05 19:50:58
【问题描述】:

我正在从文本文件中获取输入,并尝试在遇到“\n”字符时拆分文本,但它不会拆分任何内容。我在制表符和空格上试过了,效果很好。由于某种原因,它不适用于换行符。它与我获取字符串的方式有关吗?我正在将文件传送到程序中。当我在 IDLE 上尝试相同的代码行时,它工作正常。

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


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

【问题讨论】:

  • 文件是在 Windows 机器上创建的吗?如果是这样,行尾可能是\r\n

标签: python string methods split newline


【解决方案1】:

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 < 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 :

【讨论】:

  • 这真的是答案吗?!!
  • @GrijeshChauhan:为什么不呢?
  • @MartijnPieters 实际上我的问题是 OP
  • 我的程序中有一个循环,但它仍然不起作用。
  • @HarryHarry:我的第一个版本会在遇到空行时完成,这可能是问题所在。请查看我的更新答案。
【解决方案2】:

要在换行符上拆分多行字符串,您通常会改用str.splitlines(),它处理不同的换行符约定:

>>> '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()

【讨论】:

  • \n 上拆分仍会拆分,但 OP 说“它不会拆分任何内容。”
  • @RichieHindle:如果使用\r,它不会分裂。不太可能,我会答应你,但仍然。
  • 您需要一台时间机器(或工作的 MacOS
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 1970-01-01
  • 2015-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多