-1

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'
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
cody123
  • 2,040
  • 24
  • 29

2 Answers2

3

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, f.e. here: What exactly does the .join() method do?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 1
    Why not just use repr? – Mad Physicist Aug 04 '18 at 15:56
  • 1
    I mean that `str(x) if not isinstance(x,str) else "'{}'".format(x)` is basically just `repr(x)` for the values given here. Sorry my comment wasn't clear. – Mad Physicist Aug 04 '18 at 16:36
  • @MadPhysicist `s = repr([1518785613920, 1, 19, 3099, 'abc', 0, 'def'])` is `[1518785613920, 1, 19, 3099, 'abc', 0, 'def']` - inclusively the starting `[` and ending `]` which would have to be removed - you could do `repr(data).strip("[]")` - valid point – Patrick Artner Aug 04 '18 at 16:46
  • 1
    Not really what I'm saying. I'm saying to do `', '.join(map(repr, data))` or so. The long conditional expression *inside* the generator is what I'm suggesting you can shorten. – Mad Physicist Aug 04 '18 at 19:02
0

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.

dmvrtx
  • 168
  • 1
  • 2
  • 7