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

2

I have an example list:

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

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

    
asked by anonymous 16.06.2018 / 20:32

1 answer

4

You can use 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 understanding to apply replace to 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 slice:

minha_lista = ['#[Header]', '#Application Name\tLCsolution', '#Version\t1.24']
minha_lista[:2] = [s.replace('#', '') for s in minha_lista[:2]]
    
17.06.2018 / 01:05