Home > Mobile >  How to add string between processing strings
How to add string between processing strings

Time:04-26

condition 1

  • I have strings 'hello world joe'
  • I need to add * and or between them
  • Expected out >> '*hello* or *world* or *joe*'

condition 2

There is exclusion list is there for adding * ['or', 'and' 'not']

  • If the input is hello or world and joe

  • Expected out >> '*hello* or *world* and *joe*'

If any space ' ' or is there then it has to add string or if and and not is coming between the string then no need to add * between them

Code is below for condition1 how to incorporate condition2 also

value = 'hello world joe'
exp = ' or '.join([f'*{word.strip()}*' for word in value.split(' ')])
print(exp)
exclusion_list = ['or', 'and', 'not']

CodePudding user response:

You can use:

# 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*'

CodePudding user response:

You could use re.sub here with an alternation:

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'*\1*', inp)
print(output)  # *hello* or *world* and *joe*

CodePudding user response:

This can do the job:

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)

Output:

*hello* or *world* and *joe* or *joe*
  • Related