简体   繁体   中英

How to Concatenate string with list in python within for loop

i've some problem to join the string with my variable and some string within the list, here's the example:

i have some list :

my_list = ['about.html', 'contact.html', 'home.html']

and some var:

my_var = 'localhost:8000/'

i want to join the var with the list so i have something like:

my_finished_list = ['localhost:8000/about.html', 'localhost:8000/contact.html', 'localhost:8000/home.html']

how would you concatenate string and those list together?

使用列表理解

my_finished_list = [my_var+list_item for list_item in my_list]

Please use below code.

my_list = ['about.html', 'contact.html', 'home.html']
my_var = 'localhost:8000/'
my_finished_list=[]
for x in my_list:
    my_finished_list.append(my_var+x)
print(my_finished_list)

Result:

['localhost:8000/about.html', 'localhost:8000/contact.html', 'localhost:8000/home.html']

Try something like

my_list = ['about.html', 'contact.html', 'home.html']
for i in range(len(my_list)):
    my_list[i] = 'localhost:8000/' + my_list[i]
print(my_list)
for item in my_list:
    my_finished_list.append(my_var + item)

there is a more pythonic way but if u want it in a simple for loop this should seal the deal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM