讓 s = "*BCDE" - 從字串中獲取前 2 個字符,然后輸出應該是 "AB"。需要從字串中的數字指定的字串中獲取字符。例如 s1="ABCDERTYUIOPLKHGF" - 從字串中獲取前 12 個字符。
我嘗試使用 re.findall('\d ', string ) 獲取數字,但是如果我的字串是“*BCD1”,則會產生問題。請建議
uj5u.com熱心網友回復:
一種更簡單的方法是執行以下操作:
txt = "*BCDE"
number_list = [s for s in txt if s.isdigit()]
number_concate = int("".join(number_list))
txt_filtered = txt[len(number_list) 1:]
print(txt_filtered[:number_concate])
AB字串的輸出"*BCDE"
ABCDERTYUIOP字串的輸出"ABCDERTYUIOPLKHGF"
您正在獲取字串,如果數字存在,則對字串進行串列理解,然后加入串列并將其更改為整數以允許您相應地過濾字串。然后將字串剝離為僅字符,然后列印出答案。
uj5u.com熱心網友回復:
s = "*BCDE"
number = ""
offset = 0
for i in range(len(s)):
if s[i] == "%":
continue
elif s[i].isdigit():
number = s[i]
else:
offset = i
break
print(s[offset:int(number) offset])
輸出: AB
uj5u.com熱心網友回復:
import re
s = '*BCDERTYUIOPLKHGF'
numeral_instruction = re.search(r'%\d ',s).group(0)
start = len(numeral_instruction)
stop = start int(numeral_instruction[1:])
s[start:stop]
產出
AB
uj5u.com熱心網友回復:
您可以獲取字串中第一個非數字字符的位置(跳過 %)并將其用作獲取長度并形成子字串的基礎:
s1="ABCDERTYUIOPLKHGF"
i = next(i for i,c in enumerate(s1[1:],1) if not c.isdigit())
result = s1[i:i int(s1[1:i])]
print(result)
ABCDERTYUIOP
如果字串中的第一個數字并不總是在索引 1 處,您可以使用相同的技術跳過可變數量的字符:
s1="*:ABCDERTYUIOPLKHGF"
start = next(i for i,c in enumerate(s1) if c.isdigit())
end = next(i for i,c in enumerate(s1[start:],start) if not c.isdigit())
result = s1[end:end int(s1[start:end])]
print(result)
ABCDERTYUIOP
如果你想使用 re 模塊,你只需要第一次出現的數字,所以使用 re.search() 而不是 re.findall():
import re
m = re.search(r"\d ",s1)
result = s1[m.end():m.end() int(m.group())]
print(result)
ABCDERTYUIOP
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/340111.html
上一篇:如何從其他班級的串列中洗掉專案?
