Reputation: 39
How would I go about removing characters from the left side of a Python string? Example:
string='@!#word '
I know I can use strip('@!# ')
to get
string='word'
but I need a general code to remove all the characters that are not alphabet
Upvotes: 1
Views: 2115
Reputation: 18851
If you only want to strip characters from both sides (i.e. do not remove symbols in the middle):
string = '@!#word '
s, e = 0, len(string)
while s < e and not string[s].isalpha():
s += 1
while s < e and not string[e - 1].isalpha():
e -= 1
print(string[s:e])
Upvotes: 0
Reputation: 26039
This removes all non-alphabets and non-integers from both ends of the string while preserving special characters appearing within the string:
import re, string
name = "@!#word"
al_nums = re.sub('[\W_]+', '', string.printable)
extra_chars = ''.join([i for i in name if i not in al_nums])
print(name.strip(extra_chars))
# word
Upvotes: 0
Reputation: 705
Here's my try:
a=list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
name = "@!#word"
i=0
b=[]
for i in range(0,len(name)):
if(name[i] in a):
b.append(name[i])
b=''.join(b)
print(b)
A list is created with lower case & upper case alphabets. Individual elements of the string is tested against the list using is. If True, the element is appended to an empty list.
Finally, joining the list gives the characters that are only alphabets.
I've only just begun learning Python. Please let me know if this method isn't pythonic.
Upvotes: 0
Reputation: 51683
Only cleans at start and stop, non-regex, special chars inside will be preserved:
from string import ascii_letters as letters
text ='@!#word @! word '
def cleanMe(text):
t = list(text)
while t and t[0] not in letters:
t[:] = t[1:] # shorten list as long as non-letters are in front
while t and t[-1] not in letters:
t[:] = t[:-1] # shorten list as long as non-letters are in back
return ''.join(t)
w = cleanMe(text)
print (w)
Output:
word @! word
Upvotes: 0
Reputation: 82785
Use Regex.
import re
string='@!#word '
print(re.sub('[^A-Za-z]+', '', string))
Output:
word
Use this if you need to remove special chars on the sides.
Ex:
import string
s='@!#word '
print(s.rstrip(string.punctuation).lstrip(string.punctuation))
Output:
word
Upvotes: 2
Reputation: 6426
You can do this with a regular expression that matches the beginning of the string and all non-alpha characters after it:
import re
re.sub(r'^[A-Za-z]*', '', string)
Upvotes: 0
Reputation: 226
You can use filter function to do that with the help of string functions.
string='@!#word '
string = filter(str.isalnum, string)
print string
Upvotes: 0
Reputation: 3186
"code to remove all the characters that are not alphabet" If you are looking for this you can try using join :
string='@!#word '
new_str = ''.join(i for i in string if i.isalpha())
print(new_str)
O/p will be like :
'word'
Upvotes: 0