String concatenation from a list of string, using a praticle in front and one at the end for each element

Viewed 76

I have an array of strings:

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

I want to obtain:

s.a, s.b, s.c, s.d

I tried:

"s., ".join(fields)

Doesn't work because I need s. in front and , at the end

2 Answers

You should perform a mapping of the individual elements from 'x' to 's.x', we can do that by:

map('s.{}'.format, data)

then we can join these together by a comma:

', '.join(map('s.{}'.format, data))

this yields:

>>> ', '.join(map('s.{}'.format, data))
's.a, s.b, s.c, s.d'

Or like @JonClements says, since , we can use literal string interpolation [PEP-498]:

', '.join(f's.{d}' for d in data)

You were very close. Use a list comprehension for the operation you want to perform on every string, and then join the list of strings together:

data = ['a', 'b', 'c', 'd']
', '.join(['s.'+x for x in data])
# 's.a, s.b, s.c, s.d'
Related