Python 拆分带有多个分隔符的字符串并找到使用的分隔符 [英] Python split a string w/ multiple delimiter and find the delimiter used
问题描述
如何使用多个分隔符拆分字符串,并找出使用哪个分隔符来拆分 maxsplit 为 1 的字符串.
How to split string with multiple delimiters and find out which delimiter was used to split the string with a maxsplit of 1.
import re
string ="someText:someValue~"
re.split(":|~",string,1)
返回['someText', 'someValue~']
.在这种情况下,:"是分割字符串的分隔符.
returns ['someText', 'someValue~']
. In this case ":" was the delimiter to split the string.
如果字符串是string ="someText~someValue:"
,那么"~"将作为分割字符串的分隔符
If string is string ="someText~someValue:"
, then "~" will be delimiter to split the string
有没有办法找出使用了哪个分隔符并将其存储在变量中.
Is there a way to find out which delimitor was used and store that in a variable.
PS:someText 和 someValue 可能包含特殊字符,在 split 中不使用.例如:some-Text、some_Text、some$Text
PS: someText and someValue may contain special chars, that are not used in split. Eg: some-Text, some_Text, some$Text
推荐答案
string ="someText:someValue~"
print re.split("(:|~)",string,1)
如果你放入group,它会出现在返回的列表中.你可以从列表的1
索引中找到它.
If you put in group,it will appear in the list returned.You can find it from 1
index of list.
这篇关于Python 拆分带有多个分隔符的字符串并找到使用的分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!