Home > Software design >  what is the easiest way to create a list of strings with the same suffix or prefix in python
what is the easiest way to create a list of strings with the same suffix or prefix in python

Time:03-15

In a shell, given I have 3 strings with the same prefix named prefix_ and different suffix namely 1,2,3, I can write prefix_{1,2,3} to get 3 strings.

I want to know if python has a similar syntax to do this job. I want to make these strings a list and iterate over it.

Is there any solution ??

I surely don't want to write it like alist=['prefix_1','prefix_2','prefix_3'] lol

CodePudding user response:

You can use list comprehension for this.

new_array = [f"prefix_{i}" for i in old_array]

CodePudding user response:

You can use this:

alist=['prefix_' str(i) for i in range(1,4)]

CodePudding user response:

The shell expansion notation is equivalent to a product, you can achieve the same with itertools.product and str.join.

shell:

$ echo {a,b}x{1,2,3}
ax1 ax2 ax3 bx1 bx2 bx3

python:

from itertools import product
list(map(''.join, product(['a', 'b'], 'x', ['1', '2', '3'])))

output: ['ax1', 'ax2', 'ax3', 'bx1', 'bx2', 'bx3']

  • Related