繁体   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