Home > Software engineering >  Python - List - string value change
Python - List - string value change

Time:10-21

I have a list of am = ['a:hull', 'b:2', 'c:3']

I want to have am = ['a:london', 'b:2', 'c:3'] by using a function to change hull to london, without changing the rest.

I have tried to am = {a:london}, but it changes the whole list and i want to keep other information as it was

any help would be much appreciated

CodePudding user response:

You can access list items by using indexes, and the same way to change items. If you know the index (location) of the item in your list then you can do:

am[0] = "a:london"

Where 0 is the index of the item.

CodePudding user response:

Here's a quick function you can use:

am = ['a:hull', 'b:2', 'c:3']

def replace(lst):
    lst[0] = "a:london"
    print(lst)

replace(am)

We are just replacing the first string in the list to "a:london", then printing it out.

CodePudding user response:

you can use the built in replace() function in python.

strings = ['a:hull', 'b:2', 'c:3']

new_strings = []

for string in strings:
    new_string = string.replace("a:hull","a:london")
 
    new_strings.append(new_string)

print(new_strings)

output would be ['a:london', 'b:2', 'c:3']

  • Related