Extracting only characters from a string in Python

Question:

In Python, I want to extract only the characters from a string.

Consider I have the following string,

input = "{('players',): 24, ('year',): 28, ('money',): 19, ('ipod',): 36, ('case',): 23, ('mini',): 46}"

I want the result as,

output =  "players year money ipod case mini"

I tried to split considering only the alphabets,

word1 = st.split("[a-zA-Z]+")

But the split is not happening.

Asked By: SyncMaster

||

Answers:

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'
Answered By: sberry

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))
Answered By: chown

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
"
Answered By: FailedDev

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"))
Answered By: MK.

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’

Answered By: odin
import re
string = ''.join([i for i in re.findall('[w +/.]', string) if i.isalpha()])

#'[w +/.]' -> it will give characters numbers and punctuation, then 'if i.isalpha()' this condition will only get alphabets out of it and then join list to get expected result.
# It will remove spaces also.
Answered By: Tanmay Shrivastava

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])
Answered By: keshav wurfel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.