我有一個型別的字串
string = "[A] Assam[B] Meghalaya[C] West Bengal[D] Odisha "
Output = ['Assam', 'Meghalaya','West Bengal','Odhisa']
我嘗試了很多方法,但我總是將子字串 West Bengal 分成兩半……我無法涵蓋上面提到的邊緣情況。
我嘗試的是將字串傳遞到下面的函式中,然后將其拆分..但不作業!!!!
def remove_alpha(string):
option = ['[A]', '[B]', '[C]', '[D]']
res = ""
for i in option:
res = string.replace(i, '')
string = res
return res
uj5u.com熱心網友回復:
您可以為此使用正則運算式:
import re
string = "[A] Assam[B] Meghalaya[C] West Bengal[D] Odisha "
pattern = re.compile(r"] (.*?)(?:\[|$)")
output = pattern.findall(string.strip())
print(output)
# ['Assam', 'Meghalaya', 'West Bengal', 'Odisha']
- 它是如何作業的:https ://regex101.com/r/5peFyC/1
re模塊
uj5u.com熱心網友回復:
您可以使用以下方法拆分正則運算式模式re.split:
import re
string = "[A] Assam[B] Meghalaya[C] West Bengal[D] Odisha "
print(re.split(r"\s*\[\w\]\s*", string.strip())[1:])
請注意,我們首先通過 消除字串周圍的空格strip(),然后使用可能的空格r"\s*\[\w\]\s*"來匹配選項[A]。由于結果的第一個元素是空的,我們通過[1:]在末尾切片來洗掉它。
uj5u.com熱心網友回復:
這可以通過單行串列理解加上最后一個選項的特殊情況來完成:
[string[string.find(option[i]):string.find(option[i 1])].split(option[i])[1].strip() for i in range(len(option) - 1)] [string.split(option[-1])[1].strip()]
分解成一個回圈,并帶有一些明確的中間步驟以提高可讀性:
res = []
for i in range(len(option) - 1):
from_ind = string.find(option[i])
to_ind = string.find(option[i 1])
sub_str = string[from_ind:to_ind]
clean_sub_str = sub_str.split(option[i])[1].strip()
res.append(clean_sub_str)
# Last option add-on
res.append(string.split(option[-1])[1].strip())
print(res)
# ['Assam', 'Meghalaya', 'West Bengal', 'Odisha']
這不像使用正則運算式那樣漂亮,但在定義“選項”時允許更大的靈活性。
uj5u.com熱心網友回復:
您可以使用正則運算式拆分字串re.split(),這比.split()使用串列推導調整獲得的結果的 Python 字串更強大。
提供的解決方案不需要在拆分之前修改輸入字串,并且在輸入字串帶有整體擴展空格的情況下也可以作業,如下所示:
import re
s = " [A] Assam[B] Meghalaya [C] West Bengal [D] Odisha "
print([ r.strip() for r in re.split("\[[A-Z]\]", s) if r.strip() ] )
# gives: ['Assam', 'Meghalaya', 'West Bengal', 'Odisha']
正則運算式模式最多可
r'\[[A-Z]\]'拆分'[A]''[Z]'r.strip()洗掉包含結果的任何空格if r.strip()從拆分結果中洗掉空字串和僅包含空格的字串'\['和中的反斜杠'\]'是必需的,因為方括號在使用正則運算式模式時具有特殊含義,必須轉義[A-Z]表示從 A 到 Z 的任何大寫 ASCII 字母
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/529048.html
標籤:Pythonpython-3.x列表python-2.7网页抓取
上一篇:如何有效地使用我的腳本來糾正記錄器在R中的季節性漂移?
下一篇:如何使彈出視頻回應于移動設備
