Home > other >  How do you add space between characters except for a word?
How do you add space between characters except for a word?

Time:03-24

I have a string:

string = "abc(word)def(word)oiu"

I need the output as:

spaced = "a b c (word) d e f (word) o i u"

CodePudding user response:

One way using re.sub:

s = "abc(word)def(word)oiu"
re.sub("\(. ?\)", lambda x: x.group(0).replace(" ", ""), " ".join(s))

Output:

'a b c (word) d e f (word) o i u'

This will first put spaces in between all characters, and remove spaces that are between brackets.

CodePudding user response:

You can use the pattern '\(. ?\)|.' to separate the input into substrings that should be joined by spaces, and then use ' '.join() to insert those spaces.

We look for a (, followed by one or more characters, followed by a ). We use ? so that we stop at the next closing parenthesis we see, rather than the last ) in the string. If we can't match that pattern, we just take the next character:

import re
data = "abc(word)def(word)oiu"
result = ' '.join(re.findall(r'\(. ?\)|.', data))
print(result)

This outputs:

a b c (word) d e f (word) o i u

CodePudding user response:

Keep it simple and avoid regex trickery for a basic situation like this:

s = "abc(word)def(word)oiu"
w = '(word)'

spaced_out = f' {w} '.join(' '.join(text) for text in s.split(w))

CodePudding user response:

This can work for any given string.

string = "abc(word)def(word)oiu"
skip_word= "(word)"     
spaced_string = " ".join([char for char in string])
spaced_word =  " ".join([char for char in skip_word])

spaced = spaced_string.replace(spaced_word, skip_word)
  • Related