Home > database >  Create a list with string range
Create a list with string range

Time:05-25

I need your help:

I want to create a list looking like this ['Unnamed: 16, 'Unnamed: 17', 'Unnamed:18',....] for a range (16,60). How can I proceed?

I don't know if my question is clear but it's like doing list(range(16, 60) but with a string before each numbers.

Thank you very much for your help!!

CodePudding user response:

You can use f-strings to do so :

my_list = [f"Unnamed: {i}" for i in range(16, 60)]

# Output
['Unnamed: 16', 'Unnamed: 17', 'Unnamed: 18', 'Unnamed: 19', ...]

CodePudding user response:

I would do it following way

prefix = "Unnamed: "
lst = [prefix   str(i) for i in range(16,25)]
print(lst)

output

['Unnamed: 16', 'Unnamed: 17', 'Unnamed: 18', 'Unnamed: 19', 'Unnamed: 20', 'Unnamed: 21', 'Unnamed: 22', 'Unnamed: 23', 'Unnamed: 24']

Note: I used othre range for brevity sake. You might elect to use one of string formatting method instead.

CodePudding user response:

You can do it using map as,

list(map(lambda x: f'Unnamed: {x}', range(16, 60)))

CodePudding user response:

You can use f strings

name = 'Unamed:'
list = [f"{prefix} {i}" for i in range(16, 60)]
print(list)

CodePudding user response:

my_list = []

for i in range(16, 60):

    my_list.append("Unnamed: "   str(i))

print(list)
  • Related