猿问

将字符串拆分为整数部分和字符串部分的最佳方法是什么?

我有一个像这样的字符串“ 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()


慕标5832272
浏览 215回答 3
3回答

眼眸繁星

from string import ascii_letters, digitss_int, s_str = sorted([s.strip(ascii_letters), s.strip(digits)])is_valid = s in {s_int+s_str, s_str+s_int}

潇湘沐

主要是为了娱乐:ss&nbsp; = ["11547QSD", "ABC98765", "111ABC111"]fmt = r'\A(?P<full>{0}{1})\Z'ps&nbsp; = [r'(?P<digits>\d+)', r'(?P<letters>[A-Z]+)']fs&nbsp; = [fmt.format(*sorted(ps, reverse = b)) for b in [False, True]]rs&nbsp; = [re.compile(f) for f in fs]ms&nbsp; = filter(None, (r.search(s) for s in ss for r in rs))gds = [m.groupdict() for m in ms]for gd in gds:&nbsp; &nbsp; print gd# Output:# {'digits': '11547', 'full': '11547QSD', 'letters': 'QSD'}# {'digits': '98765', 'full': 'ABC98765', 'letters': 'ABC'}
随时随地看视频慕课网APP

相关分类

Python
我要回答