Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove special characters from the beginning of a string in Python

I am getting my data from XML which may some time contain special Character at beginning like:

'This is a sample title or %&*I don't know if this is the text

I tried with : title[0].isstring() or title[0].isdigit() and then remove the character. But if there are more than one special character at the beginning, then how do I remove it? Do I need a for loop?

like image 576
Simsons Avatar asked Dec 12 '22 09:12

Simsons


2 Answers

You could use a regular expression:

import re
mystring = re.sub(r"^\W+", "", mystring)

This removes all non-alphanumeric characters from the start of your string:

Explanation:

^   # Start of string
\W+ # One or more non-alphanumeric characters
like image 173
Tim Pietzcker Avatar answered Dec 14 '22 23:12

Tim Pietzcker


>>> import re
>>> re.sub(r'^\W*', '', "%&*I don't know if this is the text")
"I don't know if this is the text"

#or

>>> "%&*I don't know if this is the text".lstrip("!@#$%^&*()")
"I don't know if this is the text"
like image 29
Adam Jurczyk Avatar answered Dec 14 '22 23:12

Adam Jurczyk