簡體   English   中英

Python:1)如何引用兩個字符串變量並在其間插入一個列表元素? 2) 我怎樣才能將 append 的字符串構造成一個列表?

[英]Python: 1) How to reference two string variables and insert a list element in between? 2) How can I append the string constructed to a list?

這是一個 .txt 文件(分號表示文件的開始):

MiddlePhrase.txt:
coke and cheeseburgers
bread and wine
beer and tacos

這是我現在擁有的代碼:

middlePhrases = open('MiddlePhrase.txt', 'r')

firstPhrase = 'I love to drink and eat '
secondPhrase = ' when I am at the beach!'

for i in middlePhrases:
    print(beginningPhrase,{},endPhrase)

目標是將'MiddlePhrase.txt'的第一行寫入一個名為'NewPhraseFile.txt'的new.txt文件,然后將'MiddlePhrase.txt'中的append以下兩行寫入'NewPhraseFile.txt'

這是所需的 output(正在寫入內容的 new.txt 文件):

NewPhraseFile.txt:
I love to drink and eat coke and cheeseburgers when I am at the beach!
I love to drink and eat bread and wine when I am at the beach!
I love to drink and eat beer and tacos when I am at the beach!

我希望這對你有用......

firstPhrase = 'I love to drink and eat '
secondPhrase = ' when I am at the beach!'

fp = open('MiddlePhrase.txt','r')
#reads each line
for i in fp:
    # getting string of desired format.
    text = firstPhrase+i.strip()+secondPhrase+'\n'
    #storing it in NewPhraseFile.txt
    with open("NewPhraseFile.txt",'a') as new:
        new.write(text)
    new.close()

NewPhraseFile.txt 中的 Output:

I love to drink and eat coke and cheeseburger when I am at the beach!
I love to drink and eat bread and wine when I am at the beach!
I love to drink and eat beer and tacos when I am at the beach!

一個簡短的版本

open('new.txt', 'a+').writelines(
    f'I love to drink and eat {x.strip()} when I am at the beach!\n'
    for x in open('mid.txt'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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