Mel*_*vin 3 python string split delimiter python-3.x
我在 Python 3 中很难将字符串拆分为特定部分。字符串基本上是一个列表,以冒号 (:) 作为分隔符。
只有当冒号 (:) 以反斜杠 (\) 为前缀时,它才不算作分隔符,而是作为列表项的一部分。
例子:
String --> I:would:like:to:find\:out:how:this\:works
Converted List --> ['I', 'would', 'like', 'to', 'find\:out', 'how', 'this\:works']
Run Code Online (Sandbox Code Playgroud)
知道这如何工作吗?
@Bertrand 我试图给你一些代码,我能够找到一个解决方法,但这可能不是最漂亮的解决方案
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)
Run Code Online (Sandbox Code Playgroud)
输出:
['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']
Run Code Online (Sandbox Code Playgroud)
您应该使用re.split并执行负向后视来检查反斜杠字符。
import re
pattern = r'(?<!\\):'
s = 'I:would:like:to:find\:out:how:this\:works'
print(re.split(pattern, s))
Run Code Online (Sandbox Code Playgroud)
输出:
['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3120 次 |
最近记录: |