[英]convert python list to tsv format for input in memsql
我正在嘗試將以下列表轉換為tsv格式。
[1518785613920, 1, 19, 3099, 'abc', 0, 'def']
我想要以下格式。 我嘗試使用循環,但它從字符串中刪除了單引號。 使用join也可以刪除單引號。
1518785613920, 1, 19, 3099, 'abc', 0, 'def'
當向您顯示列表內的字符串只是“這是一個字符串”的標記時,將顯示“單引號” 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("[]")
用於print()
Doku print()
Doku for join()
或搜索SO,例如: .join()方法到底做什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.