Skip to content
Advertisement

How do I remove a common character from each element in my list?

I’m cleaning up my data after web scraping and the list has n before each element.

SP500 = [‘nAAPL’, ‘nMSFT’, ‘nGOOG’, ‘nGOOGL’, ‘nAMZN’, ‘nTSLA’…]

How should I go about removing the n from each element?

Advertisement

Answer

If you know it is always the same pattern, you can use str.removeprefix() available for python 3.9+, in your case:

SP500 = [value.removeprefix('n') for value in SP500]

If you know it’s always the same length, you can do:

SP500 = [value[2:] for value in SP500]
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement