What if the strings in the list contain the delimiter?


#1

Question

In the context of this exercise, what if the strings in the list contain the delimiter?

Answer

If the strings in the list being joined contain the delimiter, then this can cause some unwanted results. For instance, say that you are trying to join a list of strings to create a CSV file, but some of the strings contain commas. When the join is performed, then the strings containing commas will have been further split on the commas.

strings = ['a,b,c', 'd']

joined = ','.join(strings)
print(joined) # 'a,b,c,d'

For CSV files, there are some ways to prevent an issue like this in regards to commas in a field, one of which is to surround that entry with double quotes.

However, in general, it would probably be a good idea to join on some delimiter that does not cause these types of conflicts if possible.