python - 获取替换数据(python 3.3)

标签 python string replace

例如,我有一个字符串或此类字符串的列表:

text = '000 #-tags-2-7-# 001 002 003 004 05 06 07 08 SDFGSDFG #-tags-3-9-#'
keys = ['key-1', 'key-2', 'key-3', 'key-4', 'key-5', 'key-6', 'key-7', 'key-8', 'key-9', 'key-10']

我需要替换 keys[randint(2, 7)] 结果上的 #-tags-2-7-# 和 上的 #-tags-3-9-# keys[randint(2, 7)] 等。我每次需要从 #-tags---# 获取两个整数并将其发送到 keys[randint(* , *)] 并发送结果 #-tags---#

最佳答案

您可以使用re.sub将模式 r'#-tags-(\d)-(\d)-#' 替换为所需的字符串:

import re
import random
text = '000 #-tags-2-7-# 001 002 003 004 05 06 07 08 SDFGSDFG #-tags-3-9-#'
keys = ['key-1', 'key-2', 'key-3', 'key-4', 'key-5', 'key-6', 'key-7', 'key-8', 'key-9', 'key-10']

def tag_replace(match):
    start, end = map(int, match.groups())
    return ', '.join(random.sample(keys, random.randint(start, end)))

print(re.sub(r'#-tags-(\d)-(\d)-#', tag_replace, text))

打印(随机结果,例如)

000 key-8, key-7, key-3 001 002 003 004 05 06 07 08 SDFGSDFG key-9, key-1, key-7, key-3, key-4, key-10, key-6

注意:我认为您希望将 #-tags-3-9-# 替换为 keys 中以逗号分隔的 n 项列表,其中 n = random.randint(3, 9)

关于python - 获取替换数据(python 3.3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18409851/

相关文章:

python - 从 Makefile 中终止进程

Python:通过元素计数重建列表

python - 抓取网页的 "preview"- Python

c++ - 如何在此处输出之前添加数字?

javascript - JS str 替换 Unicode 感知

python - pytest:断言几乎相等

c++ - 如何使用 fgets 获取文本并保存 std::string

javascript - Python String.startswith() 与 Javascript 中的字符串列表

json - 将元素添加到 Postgres 中的 JSON 对象

python - 在 Python 3 中替换字符串中的 unicode 字符