python 在python中为列表中的每个项目的字符串前面添加一个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2130552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:51:50  来源:igfitidea点击:

Adding a string in front of a string for each item in a list in python

pythonstringloopsfor-loop

提问by Dan

I have a list of websites in a string and I was doing a for loop to add "http" in the front if the first index is not "h" but when I return it, the list did not change.

我有一个字符串中的网站列表,如果第一个索引不是“h”,我正在做一个 for 循环在前面添加“http”,但是当我返回它时,列表没有改变。

n is my list of websites h is "http"

n 是我的网站列表 h 是“http”

for p in n:
    if p[0]!="h":
        p= h+ p
    else:
        continue
return n

when i return the list, it returns my original list and with no appending of the "http". Can somebody help me?

当我返回列表时,它返回我的原始列表并且没有附加“http”。有人可以帮助我吗?

回答by Max Shawabkeh

This could also be done using list comprehension:

这也可以使用列表理解来完成:

n = [i if i.startswith('h') else 'http' + i for i in n]

回答by Alex Martelli

You need to reassign the list item -- strings are immutable, so +=is making a new string, not mutating the old one. I.e.:

您需要重新分配列表项——字符串是不可变的,因此+=创建一个新字符串而不是改变旧字符串也是如此。IE:

for i, p in enumerate(n):
  if not p.startswith('h'):
    n[i] = 'http' + p

回答by Ignacio Vazquez-Abrams

n = [{True: '', False: 'http'}[p.startswith('h')] + p for p in n]

Don't really do this. Although it doeswork.

不要真的这样做。虽然它确实有效。

回答by YOU

>>> n=["abcd","http","xyz"]

>>> n=[x[:1]=='h' and x or 'http'+x for x in n]

>>> n
['httpabcd', 'http', 'httpxyz']