Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: delete all characters before the first letter in a string

Tags:

python

string

After a thorough search I could find how to delete all characters before a specific letter but not before any letter.

I am trying to turn a string from this:

"             This is a sentence. #contains symbol and whitespace

To this:

This is a sentence. #No symbols or whitespace

I have tried the following code, but strings such as the first example still appear.

for ch in ['\"', '[', ']', '*', '_', '-']:
     if ch in sen1:
         sen1 = sen1.replace(ch,"")

Not only does this fail to delete the double quote in the example for some unknown reason but also wouldn't work to delete the leading whitespace as it would delete all of the whitespace.

Thank you in advance.

like image 434
Chris Avatar asked Jun 24 '26 14:06

Chris


2 Answers

Instead of just removing white spaces, for removing any char before first letter, do this :

#s is your string
for i,x in enumerate(s):
    if x.isalpha()         #True if its a letter
    pos = i                   #first letter position
    break

new_str = s[pos:]
like image 98
Kaushik NP Avatar answered Jun 27 '26 04:06

Kaushik NP


import re
s = "  sthis is a sentence"

r = re.compile(r'.*?([a-zA-Z].*)')

print r.findall(s)[0]
like image 25
QuantumEnergy Avatar answered Jun 27 '26 03:06

QuantumEnergy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!