Home > Mobile >  Python 3.10 .join function questions
Python 3.10 .join function questions

Time:11-21

So let's say, i want to do something thing like this

a = ['AB', 'CD']
s = '1. \n'
print(s.join(a))

Expected Output:

1. AB
2. CD

Actual Output:

AB1.
CD1.

So my question is, How can i add something at the beginning of the string s? And also increase the number.

example:

1. ...
2. ...

CodePudding user response:

a = ['AB', 'CD']
rs = ""
for i, v in enumerate(a):
    rs  = f"{i   1}. {v}\n"
print(rs)

CodePudding user response:

You can use enumerate and a list comprehension to create that string:

a = ['AB', 'CD']

s = '\n'.join(
    f"{idx}. {val}"
    for idx, val in enumerate(a, 1))
  • Related