[英]Extracting only characters from a string in Python
在 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]+")
但分裂並沒有發生。
你可以用 re 來做,但字符串拆分方法不需要正則表達式,它需要一個字符串。
這是使用 re 的一種方法:
import re
word1 = " ".join(re.findall("[a-zA-Z]+", st))
string.split() 不采用正則表達式。 你想要這樣的東西:
re.split("[^a-zA-Z]*", "your string")
並得到一個字符串:
" ".join(re.split("[^a-zA-Z]*", "your string"))
我認為你想要所有的單詞,而不是字符。
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
"
您可以采用遍歷字符串的方法,並使用isalpha
函數來確定它是否是字母字符。 如果是,您可以將其附加到輸出字符串。
a = "Some57 996S/tr::--!!ing"
q = ""
for i in a:
if i.isalpha():
q = "".join([q,i])
這樣做呢?
>>> 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'
或者,如果您想要所有字符而不考慮單詞或空格
a = "Some57 996S/tr::--!!ing"
q = ""
for i in a:
if i.isalpha():
q = "".join([q,i])
打印 q 'SomeString'
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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.