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

Viewed 2114

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.

6 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:]

Strip all whitespace and punctuation:

>>> text.lstrip(string.punctuation + string.whitespace)
'This is a sentence. #contains symbol and whitespace'

Or, an alternative, find the first character that is an ascii letter. For example:

>>> pos = next(i for i, x in enumerate(text) if x in string.ascii_letters)
>>> text[pos:]
'This is a sentence. #contains symbol and whitespace'
import re
s = "  sthis is a sentence"

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

print r.findall(s)[0]

This is a very basic version; i.e. it uses syntax that beginners in Python will easily understand.

your_string = "1324 $$ '!'     '' # this is a sentence."
while len(your_string) > 0 and your_string[0] not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":
    your_string = your_string[1:]
print(your_string)

#prints "this is a sentence."

Pros: Simple, no imports

Cons: The while loop could be avoided if you feel comfortable using list comprehensions. Also, the string that you're comparing to could be simpler using regex.

Drop everything up to the first alpha character.

import itertools as it


s = "      -  .] *    This is a sentence. #contains symbol and whitespace"
"".join(it.dropwhile(lambda x: not x.isalpha(), s))
# 'This is a sentence. #contains symbol and whitespace'

Alternatively, iterate the string and test if each character is in a blacklist. If true strip the character, otherwise short-circuit.

def lstrip(s, blacklist=" "):    
    for c in s:
        if c in blacklist:
            s = s.lstrip(c)
            continue
        return s

lstrip(s, blacklist='\"[]*_-. ')
# 'This is a sentence. #contains symbol and whitespace'

You can use re.sub

import re
text = "             This is a sentence. #contains symbol and whitespace"

re.sub("[^a-zA-Z]+", " ", text)

re.sub(MATCH PATTERN, REPLACE STRING, STRING TO SEARCH)

Related