为了账号安全,请及时绑定邮箱和手机立即绑定

Python 3:在特定条件下分割字符串

Python 3:在特定条件下分割字符串

鸿蒙传说 2021-04-05 04:27:30
我在将字符串拆分为Python 3中的特定部分方面遇到困难。该字符串基本上是一个以冒号(:)作为分隔符的列表。仅当冒号(:)带有反斜杠(\)前缀时,它才不算作分隔符,而是列表项的一部分。例子:String --> I:would:like:to:find\:out:how:this\:worksConverted List --> ['I', 'would', 'like', 'to', 'find\:out', 'how', 'this\:works']知道这怎么工作吗?我正在尝试为您提供一些代码,并且我能够找出一种解决方法,但这可能不是最漂亮的解决方案text = "I:would:like:to:find\:out:how:this\:works"values = text.split(":")new = []concat = Falsetemp = Nonefor element in values:    # when one element ends with \\    if element.endswith("\\"):        temp = element        concat = True    # when the following element ends with  \\     # concatenate both before appending them to new list    elif element.endswith("\\") and temp is not None:        temp = temp + ":" + element        concat = True   # when the following element does not end with \\   # append and set concat to False and temp to None    elif concat is True:        new.append(temp + ":" + element)        concat = False        temp = None   # Append element to new list    else:        new.append(element)print(new)输出:['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']
查看完整描述

3 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

您应该使用re.split并在后面进行负向查找来检查反斜杠字符。


import re

pattern = r'(?<!\\):'

s = 'I:would:like:to:find\:out:how:this\:works'

print(re.split(pattern, s))

输出:


['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']


查看完整回答
反对 回复 2021-04-13
?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

您可以将“:\”替换为某些内容(只需确保此内容在其他位置的字符串中不存在...您可以使用长期项或其他内容),然后用“:”分隔放回原处。


[x.replace("$","\:") for x in str1.replace("\:","$").split(":")]

解释:


str1 = 'I:would:like:to:find\:out:how:this\:works'

将“:”替换为“ $”(或其他):


str1.replace("\:","$")

Out: 'I:would:like:to:find$out:how:this$works'

现在以“:”分隔


str1.replace("\:","$").split(":")

Out: ['I', 'would', 'like', 'to', 'find$out', 'how', 'this$works']

并为每个元素将“ $”替换为“:”:


[x.replace("$","\:") for x in str1.replace("\:","$").split(":")]

Out: ['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']


查看完整回答
反对 回复 2021-04-13
?
九州编程

TA贡献1785条经验 获得超4个赞

用 re.split


前任:


import re

s = "I:would:like:to:find\:out:how:this\:works"

print( re.split(r"(?<=\w):", s) )

输出:


['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']


查看完整回答
反对 回复 2021-04-13
  • 3 回答
  • 0 关注
  • 202 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号