In Python, I want to extract only the characters from a string.
Consider I have the following string,
input = \"{(\'players\',): 24, (\'year\',): 28
I think that you want all words, not characters.
result = re.findall(r"(?i)\b[a-z]+\b", subject)
Explanation:
"
\b # Assert position at a word boundary
[a-z] # Match a single character in the range between “a” and “z”
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
\b # Assert position at a word boundary
"
You could do it with re, but the string split method doesnt take a regex, it takes a string.
Heres one way to do it with re:
import re
word1 = " ".join(re.findall("[a-zA-Z]+", st))
Or if you want all characters regardless of words or empty spaces
a = "Some57 996S/tr::--!!ing"
q = ""
for i in a:
if i.isalpha():
q = "".join([q,i])
print q 'SomeString'
What about doing this?
>>> import ast
>>> " ".join([k[0] for k in ast.literal_eval("{('players',): 24, ('year',): 28, ('money',): 19, ('ipod',): 36, ('case',): 23, ('mini',): 46}").keys()])
'case mini year money ipod players'
string.split() doesn't take regular expressions. You want something like:
re.split("[^a-zA-Z]*", "your string")
and to get a string:
" ".join(re.split("[^a-zA-Z]*", "your string"))
You can take the approach of iterating through the string, and using the isalpha
function to determine if it's a alpha character or not. If it is you can append it to the output string.
a = "Some57 996S/tr::--!!ing"
q = ""
for i in a:
if i.isalpha():
q = "".join([q,i])