0

I'm trying to convert a list into a string and prepend/append some other text each part. So far I'm doing it in a loop but wondering if there's a cleaner way of achieving this?

items = ['A', 'B', 'C']
join_str = ''
for item in items:
    join_str += 'PRE-' + var + '-MID-' + var + '-POST, '

# RESULT
# PRE-A-MID-A-POST, PRE-B-MID-B-POST, PRE-C-MID-C-POST
Carl
  • 1,346
  • 15
  • 35
  • 1
    You can benefit slightly by using f-strings, instead of adding strings. `", ".join([f"PRE-{a}-MID-{a}-POST" for a in items])` – AnkurSaxena Feb 01 '21 at 23:53
  • 2
    Does this answer your question? [Prepend the same string to all items in a list](https://stackoverflow.com/questions/13331419/prepend-the-same-string-to-all-items-in-a-list) – Gino Mempin Feb 01 '21 at 23:55
  • Does this answer your question? [Appending the same string to a list of strings in Python](https://stackoverflow.com/q/2050637/2745495) – Gino Mempin Feb 01 '21 at 23:56
  • This loop seems fine to me. – wim Feb 01 '21 at 23:58
  • @GinoMempin - yup, that definitely helps. Thank you – Carl Feb 01 '21 at 23:59

3 Answers3

1

A combination of list comprehension and string format can make it much cleaner.

>>> items = ['A', 'B', 'C'] 
>>> ', 'join(["PRE-{0}-MID-{0}-POST".format(i) for i in items])
'PRE-A-MID-A-POST, PRE-B-MID-B-POS', PRE-C-MID-C-POST'

Carl
  • 1,346
  • 15
  • 35
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
  • Thanks perfect. Thank you. I've added in a ', '.join(...) to get it into a single comma delimited string. – Carl Feb 02 '21 at 00:00
1

You can use str.join and map your string format to each value in the list:

', '.join(map('PRE-{0}-MID-{0}-POST'.format, items))

Or using a comprehension and f-strings:

', '.join(f'PRE-{i}-MID-{i}-POST' for i in items)

Output for both:

'PRE-A-MID-A-POST, PRE-B-MID-B-POST, PRE-C-MID-C-POST'
Jab
  • 26,853
  • 21
  • 75
  • 114
0

While Ahsanul has the correct answer, I think it's a bit more readable if you combine f-strings with the list comprehension.

items = ['A', 'B', 'C'] 
new_list = [f"pre-{i}-mid-{i}-post" for i in items]

Putting the "f" in front of your string (you need to use double-quotes) lets you place variables directly into a string.

For example:

apples = 5
print(f"I ate this many apples: {apples}")

prints

I ate this many apples: 5
mdeverna
  • 322
  • 3
  • 9