如何在处理字符串之间添加字符串
How to add string between processing strings
条件 1
- 我有字符串'hello world joe'
- 我需要在它们之间添加
*
和 or
- 预计结束 >>
'*hello* or *world* or *joe*'
条件 2
有排除列表可以添加 *
['or', 'and' 'not']
如果输入是hello or world and joe
预期结果 >> '*hello* or *world* and *joe*'
如果有 space ' '
或 +
那么它必须添加字符串 or
如果 and
和 not
即将到来在字符串之间则无需在它们之间添加 *
条件 1 的代码如下,如何合并条件 2
value = 'hello world joe'
exp = ' or '.join([f'*{word.strip()}*' for word in value.split(' ')])
print(exp)
exclusion_list = ['or', 'and', 'not']
您可以使用:
# value = 'hello or world and joe'
>>> ' '.join(f'*{word}*' if word not in exclusion_list else word
for word in value.split())
'*hello* or *world* and *joe*'
您可以在此处使用 re.sub
并交替使用:
inp = "hello or world and joe"
terms = ['or', 'and', 'not']
regex = r'(?!\b(?:' + '|'.join(terms) + r')\b)'
output = re.sub(regex + r'\b(\w+)\b', r'**', inp)
print(output) # *hello* or *world* and *joe*
这可以完成这项工作:
value = 'hello or world and joe joe'
exclusion_list = ['or', 'and', 'not']
value = '*' + value.replace(' ','* or *') + '*'
for w in exclusion_list:
value = value.replace(f'or *{w}* or', w)
print(value)
输出:
*hello* or *world* and *joe* or *joe*
条件 1
- 我有字符串'hello world joe'
- 我需要在它们之间添加
*
和or
- 预计结束 >>
'*hello* or *world* or *joe*'
条件 2
有排除列表可以添加 *
['or', 'and' 'not']
如果输入是
hello or world and joe
预期结果 >>
'*hello* or *world* and *joe*'
如果有 space ' '
或 +
那么它必须添加字符串 or
如果 and
和 not
即将到来在字符串之间则无需在它们之间添加 *
条件 1 的代码如下,如何合并条件 2
value = 'hello world joe'
exp = ' or '.join([f'*{word.strip()}*' for word in value.split(' ')])
print(exp)
exclusion_list = ['or', 'and', 'not']
您可以使用:
# value = 'hello or world and joe'
>>> ' '.join(f'*{word}*' if word not in exclusion_list else word
for word in value.split())
'*hello* or *world* and *joe*'
您可以在此处使用 re.sub
并交替使用:
inp = "hello or world and joe"
terms = ['or', 'and', 'not']
regex = r'(?!\b(?:' + '|'.join(terms) + r')\b)'
output = re.sub(regex + r'\b(\w+)\b', r'**', inp)
print(output) # *hello* or *world* and *joe*
这可以完成这项工作:
value = 'hello or world and joe joe'
exclusion_list = ['or', 'and', 'not']
value = '*' + value.replace(' ','* or *') + '*'
for w in exclusion_list:
value = value.replace(f'or *{w}* or', w)
print(value)
输出:
*hello* or *world* and *joe* or *joe*