python - Python 3:在特定条件下拆分字符串
问题描述
我很难在 Python 3 中将字符串拆分为特定部分。字符串基本上是一个以冒号 (:) 作为分隔符的列表。
仅当冒号 (:) 以反斜杠 (\) 为前缀时,它才算作分隔符,而是列表项的一部分。
例子:
String --> I:would:like:to:find\:out:how:this\:works
Converted List --> ['I', 'would', 'like', 'to', 'find\:out', 'how', 'this\:works']
知道这如何工作吗?
@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)
输出:
['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']
解决方案
您应该使用re.split并执行否定的lookbehind 来检查反斜杠字符。
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']
推荐阅读
- javascript - 我在一个组件中渲染多个道具,而不是在多个组件中渲染多个道具
- mysql - 左连接的 SQL Null 为 0?
- d3.js - 从图像创建 d3 多边形(二进制蒙版)
- android - React-native:Android依赖有不同的版本
- go - 加密聊天中的“运行时错误:切片超出范围”
- ajax - 向 WebApi 发出 ajax 请求时出现错误 0
- delphi-2010 - delphi如何设置段落标签的宽度?
- python - 我想让用户通过命令行文本编辑器在 python 中编辑文件
- c# - C# 中的 Linq 语句,带有 Any() 的多个过滤器
- javascript - 即使使用 .on,Ajax 调用也只能工作一次