Skip to main content
 首页 » 编程设计

python之基于特定模式和编辑字符串的拆分

2024年11月24日23del

我正在尝试根据特定模式拆分字符串,以便稍后在添加几个字符后重新加入它。

这是我的字符串示例:“123\babc\b:123”,我需要将其转换为“123\babc\\"b\":123”。我需要在很长的字符串中多次执行此操作。我尝试了以下变体:

regex = r"(\\b[a-zA-Z]+)\\b:" 
test_str = "123\\babc\\b:123" 
x = re.split(regex, test_str) 

但它并没有在我加入的正确位置 split 。有没有另一种方法/另一种 split 和加入的方法?

请您参考如下方法:

你是对的,你可以按照建议使用 re.split 来完成。您可以按 \b 拆分,然后使用特定分隔符重建输出(并在需要时保留 \b)。

举个例子:

# Import module 
import re 
 
string = "123\\babc\\b:123" 
 
# Split by "\n" 
list_sliced = re.split(r'\\b', "123\\babc\\b:123") 
print(list_sliced) 
# ['123', 'abc', ':123'] 
 
# Define your custom separator 
custom_sep = '\\\\"b\\"' 
# Build your new output 
output = list_sliced[0] 
# Iterate over each word 
for i, word in enumerate(list_sliced[1:]): 
    # Chose the separator according the parity (since we don't want to change the first "\b") 
    sep = "\\\\b" 
    if i % 2 ==  1: 
        sep = custom_sep 
    # Update output 
    output += sep + word 
 
print(output) 
# 123\\babc\\"b\":123