繁体   English   中英

如何拆分字符串并保持模式

[英]How to split a string and keeping the pattern

这就是字符串拆分现在对我有用的方式:

output = string.encode('UTF8').split('}/n}')[0]
output += '}\n}'

但我想知道是否有更多的pythonic方式来做到这一点。

目标是在'} / n}之前获取所有内容,包括'} / n}'

这可能是str.partition一个很好的str.partition

string = '012za}/n}ddfsdfk'

parts = string.partition('}/n}')
# ('012za', '}/n}', 'ddfsdfk')

''.join(parts[:-1])
# 012za}/n}

或者,您可以使用str.index显式找到它。

repl = '}/n}'

string[:string.index(repl) + len(repl)]
# 012za}/n}

这可能比使用str.find更好,因为如果找不到子字符串会引发异常,而不是产生无意义的结果。

似乎任何“更优雅”都需要正则表达式。

import re
re.search('(.*?}/n})', string).group(0)
# 012za}/n}

可以使用re.split()来完成 - 关键是在分割模式周围放置parens以保留您分割的内容:

import re

output = "".join(re.split(r'(}/n})', string.encode('UTF8'))[:2])

但是,我怀疑这是实现你想要的最有效也是最恐怖的方式。 即我不认为这自然是一种分裂的问题。 例如:

tag = '}/n}'

encoded = string.encode('UTF8')

output = encoded[:encoded.index(tag)] + tag

或者如果你坚持单行:

output = (lambda string, tag: string[:string.index(tag)] + tag)(string.encode('UTF8'), '}/n}')

或返回正则表达式:

output = re.match(r".*}/n}", string.encode('UTF8')).group(0)
>>> string_to_split = 'first item{\n{second item'
>>> sep = '{\n{'
>>> output = [item + sep for item in string_to_split.split(sep)]
NOTE: output = ['first item{\n{', 'second item{\n{']

然后你可以使用结果:

for item_with_delimiter in output:
    ...

如果你不确定行结尾会是什么,查找os.linesep可能会有用。 os.linesep是当前操作系统下的行结尾,所以在Windows下为'\\r\\n' ,在Linux或Mac下为'\\n' 它取决于输入数据的来源,以及您的代码在整个环境中的灵活性。

在某个短语之后改编自Slice字符串? ,你可以结合使用find和slice来获取字符串的第一部分并保留}/n}

str = "012za}/n}ddfsdfk"
str[:str.find("}/n}")+4]

会导致012za}/n}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM