简体   繁体   中英

convert python list to tsv format for input in memsql

I am trying to convert below list to tsv format.

[1518785613920, 1, 19, 3099, 'abc', 0, 'def']

I want below format. I tried to do using loop but it's removing single quotes from Strings. With join also it is removing single quotes.

1518785613920, 1, 19, 3099, 'abc', 0, 'def'

The "single quotes" python is displaying when showing you the strings inside a list are just markers for "this is a string". If you need them as output, you can simply add singleticks to your string itself - it will then be displayed with doubleticks:

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=","

Output:

[1, "'some data'", 2, 4] 
1, 'some data', 2, 4

You can simply include the single ticks in your output:

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=", ")

Output:

 1518785613920, 1, 19, 3099, 'abc', 0, 'def'

If you want to write it into a file, you can construct an output like so:

# 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

As mentioned by MadPhysicist thats about the same as

s = repr(data).strip("[]")

Doku for print()
Doku for join() or search SO, fe here: What exactly does the .join() method do?

You probably want to use csv.writer which:

  1. Comes with the standard library
  2. Covers various edge-cases with quotes in your strings

Together with io.StringIO it will allow you to build in-memory string which you can pass further.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM