Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]!="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?

like image 691
Dan Avatar asked Jan 25 '10 06:01

Dan


People also ask

How do you add a string to the front of a string in Python?

The easiest way of concatenating strings is to use the + or the += operator. The + operator is used both for adding numbers and strings; in programming we say that the operator is overloaded. Two strings are added using the + operator.

How do you concatenate a string with each element in a list Python?

Using join() method to concatenate items in a list to a single string. The join() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string.

How do you add an element to the infront of a list in Python?

Use list. insert() to add an element to the front of a list. Call a_list. insert(index, object) on a_list with 0 as index to insert object at the front of a_list .

How do I add multiple strings to a list in Python?

extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values. So you can use list. append() to append a single value, and list. extend() to append multiple values.


2 Answers

This could also be done using list comprehension:

n = [i if i.startswith('h') else 'http' + i for i in n]
like image 176
Max Shawabkeh Avatar answered Nov 11 '22 04:11

Max Shawabkeh


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
like image 25
Alex Martelli Avatar answered Nov 11 '22 03:11

Alex Martelli