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

Syn*_*ter 26 python regex string

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

考虑我有以下字符串,

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

我希望结果为,

output =  "players year money ipod case mini"
Run Code Online (Sandbox Code Playgroud)

考虑到只有字母表,我试图分开,

word1 = st.split("[a-zA-Z]+")
Run Code Online (Sandbox Code Playgroud)

但这种分裂并没有发生.

cho*_*own 38

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

以下是re的一种方法:

import re
word1 = " ".join(re.findall("[a-zA-Z]+", st))
Run Code Online (Sandbox Code Playgroud)


MK.*_*MK. 8

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

re.split("[^a-zA-Z]*", "your string")
Run Code Online (Sandbox Code Playgroud)

并获得一个字符串:

" ".join(re.split("[^a-zA-Z]*", "your string"))
Run Code Online (Sandbox Code Playgroud)


Fai*_*Dev 6

我想你想要所有的话,而不是字符.

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

说明:

"
\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
"
Run Code Online (Sandbox Code Playgroud)

  • @ julio.alegria你不是在正则表达式面前看到(?i)吗? (2认同)