Reputation: 4192
If I had a string that looked like this:
hello my name is12345 blah blah things
and another one that looked like this:
slim shady4321 oooh la la
How would I grab only the characters that come before the integers?
Is the best way to loop through all of the characters in the string and check whether the character is an integer and then break from the loop?
Upvotes: 0
Views: 466
Reputation:
No regex, no imports, just simple built in class.
s = 'hello my name is12345 blah blah things'
ss = 'slim shady4321 oooh la la'
w = ''
for c in ss: # OR use the below
if str(c).isalpha() or str(c).isspace(): # if not str(c).isdigit():
w += c
else:
break;
print(w)
output:
hello my name is
slim shady
Upvotes: 0
Reputation: 122
I would go for simplicity:
s = "hello my name is12345 blah foo432423 blah things"
words = s.split(' ')
for word in words:
if not word.isalpha():
print(word.rstrip('0123456789'))
This splits your string into words and check every single one if it contains only letters. If not (what we are looking for), we take that word and remove trailing numbers. Gives you:
is
foo
Upvotes: 0
Reputation: 6922
You could use the following regex:
^\D*
Explanation:
^
: Start symbol (make sure the match is from beginning of string)
\D*
:Sequence of characters that are non-digits.
(Assuming that in your examples you only want to retrieve hello my name is
and slim shady
).
Upvotes: 1
Reputation: 695
You could use positive look ahead. Match all non-digit characters before a digit.
\D*(?=\d)
Upvotes: 0
Reputation: 127
you can use regular expression to solve your problem (while using search pattern from user ctwheels)
import re
pattern = '\D+(?=\d)'
string1 = 'hello my name is12345 blah blah things'
string2 = 'slim shady4321 oooh la la'
match = re.search(pattern, string1)
match.group(0)
will return
'hello my name is'
Upvotes: 0