关于Python中字符串操作的问题

2024-10-02 00:19:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,正在练习文件操作。我写了这个程序:

myfile = open('test3.txt', 'w+')
myfile.writelines(['Doctor', 'Subramanian', 'Swamy', 'Virat', 'Hindustan', 'Sangam'])

其输出如下: DoctorSubramanianSwamyViratHindustanSangam

如何在最终输出中的列表项之间添加空格,以便最终输出为Doctor Subramanian Swamy Virat Hindustan Sangam


Tags: 文件程序txtwritelinesopenmyfiledoctor新手
2条回答

可以尝试使用相同的.strip()方法剥离它吗

value = "'"

list1 = []

for item in list2:
    list1.append(item.strip("{0}".format(value)))

试试看,让我知道

根据我对您问题的理解,您希望在最终输出的列表元素之间添加空格。一种可能的解决办法是:

myfile = open('test3.txt', 'w+')
list = ['Doctor', 'Subramanian', 'Swamy', 'Virat', 'Hindustan', 'Sangam']
for l in list:
    myfile.write(l+' ')

特别是,此行myfile.write(l+' ')将在写入每个元素后添加一个空格

相关问题 更多 >

    热门问题