在Python中仅从字符串中提取字符

时间:2011-11-20 04:13:19

标签: python regex string

在Python中,我只想从字符串中提取字符。

考虑我有以下字符串,

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

我希望结果为,

output =  "players year money ipod case mini"

我只考虑字母,

试图分开
word1 = st.split("[a-zA-Z]+")

但这种分裂并没有发生。

7 个答案:

答案 0 :(得分:37)

你可以用re来做,但字符串拆分方法不带正则表达式,它需要一个字符串。

以下是使用re执行此操作的一种方法:

import re
word1 = " ".join(re.findall("[a-zA-Z]+", st))

答案 1 :(得分:6)

string.split()不接受正则表达式。 你想要这样的东西:

re.split("[^a-zA-Z]*", "your string")

并获取字符串:

" ".join(re.split("[^a-zA-Z]*", "your string"))

答案 2 :(得分:5)

我认为你想要所有的单词,而不是字符。

result = re.findall(r"(?i)\b[a-z]+\b", subject)

<强>解释

"
\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
"

答案 3 :(得分:2)

这样做怎么办?

>>> 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'

答案 4 :(得分:1)

或者如果您想要所有字符而不管单词或空格

    a = "Some57 996S/tr::--!!ing"
    q = ""
    for i in a:
        if i.isalpha():
            q = "".join([q,i])

打印q 'SomeString'

答案 5 :(得分:0)

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.

答案 6 :(得分:0)

您可以采用遍历字符串的方法,并使用isalpha函数来确定它是否是字母字符。如果是,则可以将其附加到输出字符串。

a = "Some57 996S/tr::--!!ing"
q = ""
for i in a:
    if i.isalpha():
        q = "".join([q,i])