Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a integer iteration into a string in python?

So this is my problem:

first I iterate

for i in range(1,21):
    print (i)

then I have a variable basename="Station"

I want a result where the output is Station_1.txt, Station_2.txt etc.

I managed to add the "_" to the variable basename like

mylist1 = ("_")
s = (basename)
for item in mylist1:
    s += item

but now I have the problem on how to get the iteration on top of the variable basename, I could get is as it own like "Station_, 1, Station_, 2" but not inside the string itself.

Sorry, a total beginner here :)

like image 424
Alexandra Avatar asked Dec 07 '22 13:12

Alexandra


2 Answers

You can do this in one line! Try the following:

basename = "Station"
result = ["{}_{}.txt".format(basename, i) for i in range(1, 21)]
print(result)`

 >> ['Station_1.txt','Station_2.txt','Station_3.txt', 
     'Station_4.txt','Station_5.txt','Station_6.txt', 
     'Station_7.txt','Station_8.txt','Station_9.txt', 
     'Station_10.txt','Station_11.txt',Station_12.txt',
     'Station_13.txt','Station_14.txt','Station_15.txt',
     'Station_16.txt','Station_17.txt','Station_18.txt',
     'Station_19.txt','Station_20.txt']`
like image 51
tma Avatar answered Dec 28 '22 23:12

tma


Do you want something like this?

basename = "Station"
for i in range(1, 21):
    value = basename + "_" + str(i) + ".txt"
    print(value)

output:

Station_1.txt
Station_2.txt
Station_3.txt
Station_4.txt
Station_5.txt
Station_6.txt
Station_7.txt
Station_8.txt
Station_9.txt
Station_10.txt
Station_11.txt
Station_12.txt
Station_13.txt
Station_14.txt
Station_15.txt
Station_16.txt
Station_17.txt
Station_18.txt
Station_19.txt
Station_20.txt
like image 29
Taohidul Islam Avatar answered Dec 28 '22 23:12

Taohidul Islam