python:拆分数字和字母相遇的字符串 (1234abcd-->1234, abcd)
python: splitting strings where numbers and letters meet (1234abcd-->1234, abcd)
我有一个由数字和字母组成的字符串:string = 'this1234is5678it'
,我希望 string.split()
输出给我一个像 ['this', '1234', 'is', '5678', 'it']
这样的列表,在数字和字母的位置拆分遇到。有没有简单的方法可以做到这一点?
您可以为此使用正则表达式。
import re
s = 'this1234is5678it'
re.split('(\d+)',s)
运行 示例 http://ideone.com/JsSScE
输出['this', '1234', 'is', '5678', 'it']
更新
Steve Rumbalski 在评论中提到正则表达式中括号的重要性。他引用文档:
If capturing parentheses are used in pattern, then the text of all
groups in the pattern are also returned as part of the resulting
list." Without the parenthesis the result would be ['this', 'is',
'it'].
我有一个由数字和字母组成的字符串:string = 'this1234is5678it'
,我希望 string.split()
输出给我一个像 ['this', '1234', 'is', '5678', 'it']
这样的列表,在数字和字母的位置拆分遇到。有没有简单的方法可以做到这一点?
您可以为此使用正则表达式。
import re
s = 'this1234is5678it'
re.split('(\d+)',s)
运行 示例 http://ideone.com/JsSScE
输出['this', '1234', 'is', '5678', 'it']
更新
Steve Rumbalski 在评论中提到正则表达式中括号的重要性。他引用文档:
If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list." Without the parenthesis the result would be ['this', 'is', 'it'].