Litwos
Litwos

Reputation: 1338

Clean way to join tuples to string

Is there a cleaner, more Pythonic way to perform the following on a list of tuple values:

list_stops = [(-122.4079,37.78356),
              (-122.404,37.782)]
str_join = ''
for i in list_stops:
    coords_str = str(i[0]) + ',' + str(i[1]) + ';'
    str_join = str_join + coords_str

final_str = str_join[:-1]

I need to obtain a string that joins all tuple values, but the pairs need to be separated by a ';' sign. Example output for my 'final_str':

-122.4079,37.78356;-122.404,37.782

Upvotes: 0

Views: 77

Answers (3)

Martin Evans
Martin Evans

Reputation: 46759

If they are always just pairs:

list_stops = [(-122.4079, 37.78356), (-122.404, 37.782)]
final_str = ';'.join('{},{}'.format(p1, p2) for p1, p2 in list_stops)

print final_str

Giving you:

-122.4079,37.78356;-122.404,37.782

If you need to ensure that only pairs are used, this approach would stop with a ValueError if an incorrect number of arguments was given which could be useful.

Upvotes: 2

Satya
Satya

Reputation: 5907

You can even try a list comprehenssion as below:

';'.join([','.join([str(x) for x in y]) for y in list_stops])
o/p: '-122.4079,37.78356;-122.404,37.782
#Explanation
#1st i make something like ['-122.4079,37.78356', '-122.404,37.782'] by
#all inner tuples become ',' joined
#then ';' join those valuse

breaking into 2 steps for more clarity

list_1 = [','.join([str(x) for x in y]) for y in list_stops]
#['-122.4079,37.78356', '-122.404,37.782']
req_string = ';'.join(list_1)
#'-122.4079,37.78356;-122.404,37.782'

Upvotes: 3

Netwave
Netwave

Reputation: 42678

Chain two str.join, notice the use of map necesary for transforming the values to string:

list_stops = [(-122.4079,37.78356),
              (-122.404,37.782)]
";".join(",".join(map(str, x)) for x in list_stops)

'-122.4079,37.78356;-122.404,37.782'

Upvotes: 3

Related Questions