我在将字符串拆分为Python 3中的特定部分方面遇到困难。该字符串基本上是一个以冒号(:)作为分隔符的列表。
仅当冒号(:)带有反斜杠(\)前缀时,它才不算作分隔符,而是列表项的一部分。
例子:
String --> I:would:like:to:find\:out:how:this\:works
Converted 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 = False
temp = None
for 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']
阿波罗的战车
qq_花开花谢_0
九州编程
相关分类