Home > Software engineering >  How do I remove a common character from each element in my list?
How do I remove a common character from each element in my list?

Time:05-24

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?

CodePudding user response:

If you know it is always the same pattern, you can use str.removeprefix(), 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]

CodePudding user response:

You could do this:

remove_char = ['\n']
SP500 = ['\nAAPL', '\nMSFT', '\nGOOG', '\nGOOGL', '\nAMZN', '\nTSLA']
SP500 = [''.join(x for x in string if not x in remove_char) for string in SP500]

every item in the remove_char list is deleted from your list

  • Related