我想創建一個給定字串的串列,例如 'b123 xyz=1 z1$' 以便串列等于 ['b123', ' ', 'xyz', '=', '1', ' ' , 'z1', '$']
沒有空格或單個重復模式,我不知道如何將字串拆分為串列。
我嘗試在 for 回圈中創建 if 陳述句以在字串通過 isdigit 和 isalpha 到達不是數字或字母但無法區分變數和數字的字符時附加字串。
uj5u.com熱心網友回復:
您可以使用正則運算式來拆分字串。這通過使用積極的前瞻和后視來尋找無字字符來作業。
import re
sample = "b123 xyz=1 z1$"
split_sample = re.split("(?=\W)|(?:(?<=\W)(?!$))", sample)
print(split_sample)
輸出
['b123', ' ', 'xyz', '=', '1', ' ', 'z1', '$']
正則運算式解釋

uj5u.com熱心網友回復:
另一種給出相同結果的正則運算式方法是:
split_sample = re.split(r"(\ |=|\$)", sample)[:-1]
[:-1] 是洗掉最后的空字串。
uj5u.com熱心網友回復:
"""
Given the equation b123 xyz=1 z1$, break it down
into a list of variables and operators
"""
operators = [' ', '-', '/', '*', '=']
equation = 'b123 xyz=1 z1$'
equation_by_variable_and_operator = []
text = ''
for character in equation:
if character not in operators:
text = text character
elif character in operators and len(text):
equation_by_variable_and_operator.append(text)
equation_by_variable_and_operator.append(character)
text = ''
# For the final variable
equation_by_variable_and_operator.append(text)
print(equation_by_variable_and_operator)
輸出
['b123', ' ', 'xyz', '=', '1', ' ', 'z1$']
uj5u.com熱心網友回復:
一個直接的regex解決方案是;
equation = "b123 xyz=1 z1$"
equation_list = re.findall(r'\W |\w ', equation)
print(equation_list)
這也適用于字串,例如-b**10.
使用re.split()從字串開頭和結尾的分隔符回傳字串開頭和結尾的空字串(請參閱此問題)。要洗掉它們,可以將它們過濾掉,或者可以使用增加模式復雜性的后視或前瞻條件,如該問題的早期答案所示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/524442.html
標籤:Python细绳列表
下一篇:Haskell“解碼”
