How can I add a character to each element of a Python string?

Asked

Viewed 3,679 times

2

We have the following list:

list=["oi","meu","nome","é","Gustavo"]

I want to add a character at the beginning of each element of the list (added the name opa in each element manually same :p):

list=["opaoi","opameu","opanome","opaé","opaGustavo"]

How can I do this with Python?

2 answers

6


You can make a simple for

So you scroll through each index by concatenating the "opa"

lista=["oi","meu","nome","é","Gustavo"]

nova_lista = []
for item in lista:
    nova_lista.append("opa" + item)

#Mostra o resultado da nova lista
for item in nova_lista:
    print(item + "\n")

Or use the map function

Using a lambda expression x: "opa" + x and returning a list to your new list

lista=["oi","meu","nome","é","Gustavo"]

nova_lista = list(map(lambda x: "opa" + x, lista))

for item in nova_lista:
    print(item + "\n")

Use map but return to original list

Instead of returning to a new list, you can continue using the original list with the changed values

lista=["oi","meu","nome","é","Gustavo"]

lista = list(map(lambda x: "opa" + x, lista))

for item in lista:
    print(item + "\n")

And with the help of our friend Mário Feroldi, there is another solution using list lambda understanding

lista=["oi","meu","nome","é","Gustavo"]

lista = [f"opa{x}" for x in lista]

for item in lista:
    print(item + "\n")

The result of any of the methods is the same:

opaque

opanym

opae

opaGustavo

  • There is also list understanding: [f"opa{x}" for x in lista].

  • Thanks @Márioferoldi, I edited the question putting this solution more :)

4

The most direct and simple way is to use list comprehension:

result = ["opa" + item for item in list]

The expression [f(x) for x in l], where f is a function that takes an argument and returns some value, and l is any list, a new list is created by applying the function f for each item in the list l. In that case, f(x) would be the concatenation of strings "opa" and of each element x.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.