gpt4 book ai didi

python - 如何将行添加到列表中作为单个字符串项?

转载 作者:太空宇宙 更新时间:2023-11-04 08:58:55 24 4
gpt4 key购买 nike

我正在尝试向列表中添加文本行。我有以下代码:

theText = 'foo \n bar'
for line in theText:
theList.append(line)
print theList

此代码打印:

['f', 'o', 'o', ' ', '\n', ' ', 'b', 'a', 'r']

当我期待更像的东西时:

['foo ', '\n bar']

有没有办法让整行成为列表中的单个字符串项?

最佳答案

如果您想要线条并保留定界符,请使用 keepends=True 的分割线,正确的结果是 ['foo\n', 'bar'] 作为换行符在 foo 而不是 bar 的行上:

theText = 'foo \n bar'
print(theText.splitlines(True))
['foo \n', ' bar']

关于python - 如何将行添加到列表中作为单个字符串项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27554288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com