How to remove only spaces between words/letters?

Asked

Viewed 114 times

2

Supposing I have a string: str = ' p s i c ó l o g o '. Note that the string has a space before the letters, a space between the letters and a space after the letters. What I want is for the spaces between the letters to disappear, but the space that is before and what is after the letters remains. The string would look like this: str = ' psicólogo '. I even tried the str.replace(" ", "")but this would also eliminate the spaces that are before and after the letters, so: 'psicólogo'

3 answers

3

You can use Regular Expressions to delete only spaces between words. For this you can use \b to match the limit of words (see documentation).

So if we do a regex to match 1 or more spaces between two words, the regex will match all spaces in the string except the initials and endings.

With that we have the regex \b +\b and now just use regex.sub() to replace the found spaces with an empty string.

import re

regex = re.compile(r"\b +\b")
regex.sub("", "    p  s  i   c  ó   l   o   g    o    ")
# '    psicólogo    '

Repl.it with code running.

  • 1

    Could you explain why I voted no? This solution works.

2

It is possible to create a regular expression that captures only the spaces contained between two characters.

import re

regex = re.compile(r"(?<=\w)\s+(?=\w)")
print(regex.sub("", "    p  s  i   c  ó   l   o   g    o    "))

The expression (?<=\w)\s+(?=\w) can be read like this:

  • \s+ capture one more space such that...
  • (?<=\w) ...these spaces are preceded by a character...
  • (?=\w) ...and that these spaces are succeeded by a character.

1

If you want it to exist at all times one space at the beginning and another at the end, you can simply concatenate the spaces with what you tried, i.e., " " + str.replace(" ", "") + " ".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.