如何用Python正则表达式拆分字符串中的数字与文本部分?
Solution to Split Text and Numbers into Separate Elements
Got it, let's tackle this problem! You need a Python function that splits a string into alternating text and numeric elements—exactly like turning "this1is2a3string4" into ['this','1','is','2','a','3','string','4'] (I assume the "my" in your expected output was a typo for "a").
Here's a straightforward implementation using Python's re module:
import re def my_func(string): # Match one or more digits OR one or more non-digits return re.findall(r'\d+|\D+', string) # Test with your example input print(my_func("this1is2a3string4")) # Output: ['this', '1', 'is', '2', 'a', '3', 'string', '4']
How this works:
- The regex pattern
r'\d+|\D+'has two parts separated by|(which means "or"):\d+: Matches one or more consecutive numeric characters\D+: Matches one or more consecutive non-numeric characters
re.findall()scans the entire input string, extracts all matching segments in order, and returns them as a list. This handles edge cases too—like strings starting/ending with numbers (e.g.,"123hello456"becomes['123', 'hello', '456']) or strings with no numbers at all.
If you need to handle empty strings or other edge cases, you can add a quick validation check, but for your core use case, this should work perfectly.
内容的提问来源于stack exchange,提问作者user6172474
相关产品推荐
相关产品推荐

