how can i surround texts with spaces?

You can use

re.sub(r'\s*(ATK 30)\s*', r' \1 ', text)

See the regex demo.

Details

  • \s* – 0+ whitespaces
  • \b – a word boundary
  • (ATK 30) – Capturing group 1 (referred to with the \1 backreference from the replacement pattern): ATK 30
  • \s* – 0+ whitespaces

If you have a list of words and you need a dynamically built pattern use

import re
s = "Product desingATK 30Trace back. TheATK 30 is a nice device. "
keywords = ['ATK 30', 'PPK 50', 'HJF12 10']
pattern = fr'\s*({"|".join(sorted(map(re.escape, keywords),key=len,reverse=True))})\s*'
print(pattern)                       # => \s*(HJF12\ 10|ATK\ 30|PPK\ 50)\s*
print(re.sub(pattern, r' \1 ', s))  
# => Product desing ATK 30 Trace back. The ATK 30 is a nice device. 

Here, fr'\s*({"|".join(sorted(map(re.escape, keywords),key=len,reverse=True))})\s*' does the following:

  • map(re.escape, keywords) – escapes each keyword (so that ( or ? could not interfere with the task)
  • sorted(...,key=len,reverse=True) – sorts by length in descending order (the first alternative always “wins”, so it is necessary)
  • "|".join(...) – creates the alternation pattern.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top