我正在尝试将下面的列表转换为tsv格式。
[1518785613920, 1, 19, 3099, 'abc', 0, 'def']
我想要下面的格式。我试着使用循环,但它从字符串中删除了单引号。对于join,它还删除了单引号。
1518785613920, 1, 19, 3099, 'abc', 0, 'def'
发布于 2018-08-04 23:22:51
在显示列表中的字符串时,python显示的“单引号”只是"this is a string“的标记。如果你需要它们作为输出,你可以简单地在你的字符串本身中添加单号-然后它会用双号来显示:
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()
或搜索SO,f.e.这里:What exactly does the .join() method do?
https://stackoverflow.com/questions/51686386
复制相似问题