[英]Replacing strings line by line
我有一個文本文件testfile.txt,文件內容(輸入)如下所示:
Msg "how are you"
Msg "Subtraction is", 10-9
輸出應如下所示,
Msg("how are you")
Msg("Subtraction is", 10-9)
我打開文件如下
fileopening = open('testfile.txt', 'r')
fileopening.readline()
for line in fileopening:
print line.replace(' "', '(')
for line in fileopening:
print line.replace('"', ')')
但是上面的代碼實際上更改了先前轉換的空格和引號。 如何才能使它看起來像上面顯示的所需輸出? 我想將Msg作為單行並用()包裝Msg,然后轉到下一行。
我的新輸出如下所示:
Msg( "hello"
)
()
Msg( "dfsdkbfsd")
除了使用replace
,您還可以利用括號始終插入第4個位置和最后一個位置這一事實:
with open('testfile.txt', 'r') as fileopening:
next(fileopening)
for line in fileopening:
line = line.rstrip()
print('{}({})'.format(line[:3], line[4:]))
順便說一句,由於您使用的是Python3,請注意print
是一個函數,因此其參數必須用括號括起來。 使用不帶括號的print
會引發SyntaxErrors
。
解決問題的一種方法如下:
with open('testfile.txt', 'r') as f:
for line in f:
newline = line.replace(' "', '("')
newline = newline.replace('\n', ')\n')
print newline
這不會假定每一行都以Msg開頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.