[英]Formatting line breaks in python strings
我有一个字符串:
f = open("file.txt", r)
message = f.read()
print message
>>> "To: email\ntitle: add title here\nDescription: whatever here\n"
我可以这样做来分割字符串:
f_email, f_title, f_description, blank = message.split('\n')
但是,当我收到如下消息时,就会出现问题:
"To: email\ntitle: add title here\nDescription: first line\nSecond line\nthirdline\n"
当我分割字符串时,它也会分割描述。 我努力了:
f_email, f_title, f_description, blank = message.split('\n',4)
但这显然会返回ValueError,因为它将拆分更多的4个\\ n。
有什么建议么?
当您运行.split('\\n')
您将返回一个列表。 您可以在分配变量时将它们拉出列表,而不是在拆分时分配变量:
tokens = message.split('\n')
f_email = tokens[0]
f_title = tokens[1]
f_description = tokens[2]
通过检查列表的大小,可以使它不那么脆弱。 如果您知道它至少需要三个要素,则可以:
assert(len(tokens)>=3)
解决此问题的另一种方法是将内容包装在try/except
块中:
tokens = message.split('\n')
try:
f_description = tokens[2]
except:
f_description = None
这样,您就可以按照自己喜欢的方式处理更短的清单!
@Hooked为Python2提供了一个很好的答案。 由于在Python3 *
也可用于元组解包,因此您可以执行以下操作:
f_email, f_title, *f_description = tokens
详细信息在PEP 3132中
如果您不想整体使用文本,并且不希望使用低于3.x的版本来进行splat解压缩,则可以这样简单地进行操作:
email = None
title = None
description = ""
with open("test.txt", "r") as f:
for number, line in enumerate(f):
if number == 0:
email = line.strip()
elif number == 1:
title = line.strip()
else:
description += line
当您使用message.split('\\ n',2)时,您将获得三部分:第一行,第二行和剩余的一行。
使用以下形式:
f = open("file.txt")
f_email, f_title, f_description = f.read.split('\n', 2)
f.close()
或这个:
f = open("file.txt")
f_email = f.readline()
f_title = f.readline()
f_description = f.read()
f.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.