我有一个像这样的字符串“ 11547QSD”。我想将其分为“ 11547”和“ QSD”两个部分。我得到了isnumeric()函数的提示。我正在概述一下。请向我建议最好的分解方法。 str1 = "11547QSD" # is a valid string (in my context) str2 = "ABC98765" # is a valid string str3 = "111ABC111" # is not a valid string if str1.isvalid(): str1_int = str1.integer_part() str1_str = str1.string_part()
3 回答
眼眸繁星
TA贡献1873条经验 获得超9个赞
from string import ascii_letters, digits
s_int, s_str = sorted([s.strip(ascii_letters), s.strip(digits)])
is_valid = s in {s_int+s_str, s_str+s_int}
潇湘沐
TA贡献1816条经验 获得超6个赞
主要是为了娱乐:
ss = ["11547QSD", "ABC98765", "111ABC111"]
fmt = r'\A(?P<full>{0}{1})\Z'
ps = [r'(?P<digits>\d+)', r'(?P<letters>[A-Z]+)']
fs = [fmt.format(*sorted(ps, reverse = b)) for b in [False, True]]
rs = [re.compile(f) for f in fs]
ms = filter(None, (r.search(s) for s in ss for r in rs))
gds = [m.groupdict() for m in ms]
for gd in gds:
print gd
# Output:
# {'digits': '11547', 'full': '11547QSD', 'letters': 'QSD'}
# {'digits': '98765', 'full': 'ABC98765', 'letters': 'ABC'}
添加回答
举报
0/150
提交
取消