daiyue
daiyue

Reputation: 7458

python can't append a string to each element of a tuple using join

I tried to append a string to each element string in a tuple using join,

str_tup = ('country', 'town')
fields = ('_outlier'.join(key) for key in str_tup)

for key in fields:
    print(key)

I got

c_outliero_outlieru_outliern_outliert_outlierr_outliery
t_outliero_outlierw_outliern

instead of

country_outlier
town_outlier

I am wondering how to resolve the issue, using a generator here trying to save memory.

Upvotes: 2

Views: 59

Answers (2)

Laurent H.
Laurent H.

Reputation: 6526

If you are using Python 3.6+, I suggest you to use f-strings to build the generator, which are very beautiful and optimized. They really deserve to be known and widely used. Here is my proposal:

str_tup = ('country', 'town')
fields = (f'{s}_outlier' for s in str_tup)

for key in fields:
    print(key)
# country_outlier
# town_outlier

Upvotes: 2

Pieter De Clercq
Pieter De Clercq

Reputation: 1971

The join(x) function concatenates an iterable(e.g. a list) of items, placing x in between every item. What you are looking for is simple concatenation:

str_tup = ('country', 'town')
fields = (key + '_outlier' for key in str_tup)

for key in fields:
    print(key)

Upvotes: 4

Related Questions