Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protect commas on consecutive string.join() and string.split()

Tags:

python

Suppose the following code (notice the commas inside the strings):

>>> a = ['1',",2","3,"]

I need to concatenate the values into a single string. Naive example:

>>> b = ",".join(a)
>>> b
'1,,2,3,'

And later I need to split the resulting object again:

>>> b.split(',')
['1', '', '2', '3', '']

However, the result I am looking for is the original list:

['1', ',2', '3,']

What's the simplest way to protect the commas in this process? The best solution I came up with looks rather ugly.

Note: the comma is just an example. The strings can contain any character. And I can choose other characters as separators.

like image 500
Filipe Correia Avatar asked Nov 27 '25 17:11

Filipe Correia


1 Answers

The strings can contain any character.

If no matter what you use as a delimiter, there is a chance that the item itself contains the delimiter character, then use the csv module:

import csv

class PseudoFile(object):
    # http://stackoverflow.com/a/8712426/190597
    def write(self, string):
        return string
writer = csv.writer(PseudoFile())

This concatenates the items in a using commas:

a = ['1',",2","3,"]
line = writer.writerow(a)
print(line)
# 1,",2","3,"

This recovers a from line:

print(next(csv.reader([line])))
# ['1', ',2', '3,']
like image 170
unutbu Avatar answered Dec 02 '25 04:12

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!