我正在将列表卡片组写入文件中,但是我需要每个列表中的每个项目在写入时都不要在其周围加上''。
deck = [['ad','ah','ac','as'],['2d','2h','2c','2s'],['3d','3h','3c','3s'],['4d','4h','4c','4s'],['5d','5h','5c','5s'],['6d','6h','6c','6s'],['7d','7h','7c','7s'],['8d','8h','8c','8s'],['9d','9h','9c','9s'],['td','th','tc','ts'],['jd','jh','jc','js'],['qd','qh','qc','qs'],['kd','kh','kc','ks']]
f = open('list.txt','w')
for i in deck:
a=str(i)[1:-1].strip("'")+"\n"
f.writelines(a)
f.close()
在上面的代码中我看到了ive试图使用.strip(),但是这并没有起作用,因为它只删除了第一个和最后一个引号。有没有办法让文本文件看起来像这样:
ad, ah, ac, as
2d, 2h, 2c, 2s
3d, 3h, 3c, 3s
4d, 4h, 4c, 4s
etc...
答案 0 :(得分:1)
只需使用.replace("'", "")
而不是.strip("'")
。 Strip仅从字符串的左侧和右侧除去字符,而不是从中间除去字符,这就是为什么您看到在每一行上将数组打印为ad', 'ah', 'ac', 'as
的原因:
deck = [['ad','ah','ac','as'],['2d','2h','2c','2s'],['3d','3h','3c','3s'],['4d','4h','4c','4s'],['5d','5h','5c','5s'],['6d','6h','6c','6s'],['7d','7h','7c','7s'],['8d','8h','8c','8s'],['9d','9h','9c','9s'],['td','th','tc','ts'],['jd','jh','jc','js'],['qd','qh','qc','qs'],['kd','kh','kc','ks']]
f = open('list.txt','w')
for i in deck:
a=str(i)[1:-1].replace("'", "")+"\n"
f.writelines(a)
f.close()
答案 1 :(得分:1)
您可以按照以下步骤进行操作:
for each in deck:
for INDEX, EACH in enumerate(each):
if INDEX==0:
print(EACH,end='')
else:
print(','+EACH,end='')
print('\n')
产生输出:
ad,ah,ac,as
2d,2h,2c,2s
3d,3h,3c,3s
4d,4h,4c,4s
...
答案 2 :(得分:1)
使用join
将每个子列表的不同部分与', '
连接起来:
deck = [['ad','ah','ac','as'],['2d','2h','2c','2s'],['3d','3h','3c','3s'],['4d','4h','4c','4s'],['5d','5h','5c','5s'],['6d','6h','6c','6s'],['7d','7h','7c','7s'],['8d','8h','8c','8s'],['9d','9h','9c','9s'],['td','th','tc','ts'],['jd','jh','jc','js'],['qd','qh','qc','qs'],['kd','kh','kc','ks']]
with open('list.txt','w') as f:
for sublist in deck:
f.write(', '.join(sublist)+'\n')
输出(在list.txt
中):
ad, ah, ac, as
2d, 2h, 2c, 2s
3d, 3h, 3c, 3s
...
另外,请注意,最好使用with open...
来确保无论发生什么情况文件都被关闭。
答案 3 :(得分:1)
您要执行的操作是用csv fromat书写。即尝试这样的事情:
import csv
with open('list.txt','w') as f:
writer = csv.writer(f, quoting=csv.QUOTE_NONE)
writer.writerows(deck)