开发者

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

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.

n is my list of websites h is "http"

for p in n:
    if p[0开发者_Python百科]!="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?


This could also be done using list comprehension:

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


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

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


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

Don't really do this. Although it does work.


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

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜