簡體   English   中英

格式化python字符串中的換行符

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM