How to remove a specific character from some specific strings within a Python list?

Asked

Viewed 163 times

2

I have a list of examples:

['#[Header]', '#Application Name\tLCsolution', '#Version\t1.24']

I would like to know how to remove a specific character, such as the # of all elements of the list, or, if I prefer, of only a few elements, such as [0:1].

1 answer

4


You can use the replace to replace unwanted characters in your string with an empty string:

'#[Header]'.replace('#', '')  # '[Header]'

To do this in all strings in the list, just use a list comprehension to apply the replace in all elements:

minha_lista = ['#[Header]', '#Application Name\tLCsolution', '#Version\t1.24']
minha_lista = [s.replace('#', '') for s in minha_lista]

Or do the same for just one Cup:

minha_lista = ['#[Header]', '#Application Name\tLCsolution', '#Version\t1.24']
minha_lista[:2] = [s.replace('#', '') for s in minha_lista[:2]]
  • And if I want to modify the list elements by accessing the element by their content?

  • @Brunosantos can give an example of what it means?

  • lista_original = ['#flower', '#leaf', '#stone', '#tree', '#storm'] How do I remove '#' from '#stone' and '#storm' without knowing their content in the list? Just knowing that I want to alter these elements, even without knowing where they are?

  • 1

    @Brunosantos if understood well, just do minha_lista[minha_lista.index('#pedra')] = 'pedra', or minha_lista[minha_lista.index('#pedra')] = '#pedra'.replace('#', '').

  • thank you!!!!!!!

Browser other questions tagged

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