繁体   English   中英

Python string 以特定模式拆分

[英]Python string split in a specific pattern

我正在尝试以这种特定模式拆分 string:

 'ff19shh24c' -> ['f', 'f', '19s', 'h', 'h', '24c']

我设法做到了这一点:

 import re string = "ff19shh24c" parts = re.findall(r'\D+|\d+[az]{1}') print(parts) -> ['ff', '19s', 'hh', '24c']

但现在我有点卡住了。

搜索任何东西(非贪婪),然后搜索一个字母。

 import re string = "ff19shh24c" parts = re.findall(r'.*?[az]', string) print(parts)

这会给你['f', 'f', '19s', 'h', 'h', '24c']

一种可能性,找到零个或多个数字,然后是一个非数字:

 import re string = 'ff19shh24c' parts = re.findall('\d*\D', string)

output: ['f', 'f', '19s', 'h', 'h', '24c']

由于问题没有用regex或类似的标记在这里一个for循环方法

s = 'ff19shh24c' out = [] tmp = '' was_a_digit = False # keep track if the previous character was a digit for char in s: if char.isdigit(): was_a_digit = True tmp += char else: if was_a_digit: tmp += char out.append(tmp) tmp = '' was_a_digit = False else: out.append(char) print(out) #['f', 'f', '19s', 'h', 'h', '24c']

如果字符串以数字结尾,上述代码将丢失这些字符,但稍作编辑仍然可以检索它们。

这里是保存字符的方法:

 s = 'ff19shh24cX29ZZ88'... same as above # directly after the end of the for loop out.append(tmp) print(out) ['f', 'f', '19s', 'h', 'h', '24c', 'X', '29Z', 'Z', '88']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM