1

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']
1
  • 1
    Hmm... "if and and not is coming between the string then no need to add * between them". So should the result of 'hello or world and joe' be '*hello* or *world* and *joe*' or '*hello* or *world* and joe' or '*hello* or world and joe' or...? Commented Apr 26, 2022 at 7:06

3 Answers 3

2

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*'
Sign up to request clarification or add additional context in comments.

Comments

1

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*

Comments

0

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*

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.