我正在尝试将以下列表转换为tsv格式。
[1518785613920, 1, 19, 3099, 'abc', 0, 'def']
我想要以下格式。我尝试使用循环,但它从字符串中删除了单引号。使用join还可删除单引号。
1518785613920, 1, 19, 3099, 'abc', 0, 'def'
答案 0 :(得分:3)
当向您显示列表内的字符串只是“这是一个字符串”的标记时,将显示“单引号” python。如果您需要将它们作为输出,则只需在字符串本身中添加单引号-它将显示为带有双引号:
print([1,"'some data'",2,4)) # no deref, will be printed as repr(list).
print(*[1,"'some data'",2,4], sep=", ") # *[..] will deref elements+ print each with sep=","
输出:
[1, "'some data'", 2, 4]
1, 'some data', 2, 4
您只需在输出中包含单个刻度线即可。
data = [1518785613920, 1, 19, 3099, 'abc', 0, 'def']
# generator expression that adds '' around strings in the generator and prints it
# using the deref * and print's sep=", " specifier
print( *(x if not isinstance(x,str) else "'{}'".format(x) for x in data), sep=", ")
输出:
1518785613920, 1, 19, 3099, 'abc', 0, 'def'
如果要将其写入文件,可以构造如下输出:
# use join() and some generator comp to create output. join needs strings so str(int)
s = ', '.join((str(x) if not isinstance(x,str) else "'{}'".format(x) for x in data))
# s is identical to above output
正如MadPhysicist所说,与
大致相同
s = repr(data).strip("[]")
Doku for print()
Doku for join()
或搜索,例如此处:What exactly does the .join() method do?
答案 1 :(得分:0)