-1
def main():
    a = print(input().strip(" ").replace(" ", "..."))

if __name__ == "__main__":
    main()

I was creating this little program that detects any space IN BETWEEN the words and turn in to only three space, no matter how many space the user typed between words. I tried using re module but it didn't work...

  • So given input like `this is a test`, you would like to see `this...is...a...test`? – larsks Aug 30 '22 at 03:13
  • if the input is " _____hello________world____" or something similar, my expected output would be like "hello...world." – somnambulist Aug 30 '22 at 03:15
  • You may want to look into the string `split` method, which by default splits a string on whitespace. Combined with the `join` method, you can probably get what you want. – larsks Aug 30 '22 at 03:16
  • The space(s) at the beginning and the end of the string should be gone and the space(s) between words should become only three dot (...). – somnambulist Aug 30 '22 at 03:16
  • You might want to look at https://regex101.com/ to help test and debug a regular expression to accomplish this. – pknodle Aug 30 '22 at 03:17
  • Regex `"( )+"` will detect any no of space, so you can do something like this: `re.sub("( )+", "...",string)` – thisisjaymehta Aug 30 '22 at 03:36
  • 1
    "I tried using re module but it didn't work". Please update your question with your attempt at using the `re` module, so that we can help fix or improve it. – blhsing Aug 30 '22 at 03:42

4 Answers4

1

Updated with @Grismar comment:
use .split() with default parameter(None or no parameter), then consecutive whitespace are regarded as a single separator.

Here is the solution using

  • split the string with no parameter,
  • join the array with "..."
def input():
    return "     hello        world    "
def main():
    a = print("...".join(input().split()))

if __name__ == "__main__":
    main()

output: hello...world

charmian
  • 506
  • 2
  • 9
  • 2
    If you don't filter by individual spaces, but just by whitespace (the default for `.split()`), you don't need the `.filter()`. Also, don't shadow names like `input` with user-defined functions. – Grismar Aug 30 '22 at 04:25
  • @Grismar Thank you for your comment! I will update my answer. – charmian Aug 30 '22 at 04:34
0

Given there aren't any examples of input and expected output, I had to make an assumption about desired behaviour.

detects any space IN BETWEEN the words and turn in to only three space, no matter how many space the user typed between words.

It sounds like you want to look for any whitespace between words in a string and then massage that to have three spaces?


Here's a scrappy solution. It basically takes a string, splits it into individual words. We then create a list of words and adds three spaces after it (the f-string part). We can then can contaneate those new word-parts into a string. Then, finally, we can construct a sentence by joining the elements of words between the periods.

my_text = "Hello this is   a test     string with   different amount      of spaces   between  the      words .  Second sentence goes   here ."

# Splits the string based on whitespace
list_of_words = my_text.split()

# List comprehension and f-string 
list_of_words_with_spaces = [f'{word}   ' for word in list_of_words]

new_string = ''
for word in list_of_words_with_spaces:
    new_string += word

final_string = ''
for sentence in new_string.split('.'):
    if not sentence.strip(): # Check to ignore for empty sentences
        break
    final_string += sentence[:-3] + '.' # Remove the whitespace before the period

The final string looks like this:

'Hello   this   is   a   test   string   with   different   amount   of   spaces   between   the   words.   Second   sentence   goes   here.'
lummers
  • 689
  • 3
  • 8
  • 17
0

A very simple regular expression operator is the Kleene plus, written as +. It will match the preceding character one or more times. Therefore, ' +' is the regex that will match one or more spaces in a row.

To use this in python:

import re

def main():
     a = print(re.sub(r' +', '   ', input().strip(" ")))

if __name__ == "__main__":
    main()

Alternatively, a simple loop through the string can work too:

a = input().strip()
output = []
for word in a.split(' '):
    if word is not "":
        output.append(word)
print('   '.join(output))
        
J.R.
  • 66
  • 4
0

Two simple ways to get what you need:

import re

example = '  hello world   this is  an     example  '

replacement = '...'

print(replacement.join(example.split()))
print(re.sub(r'\s+', replacement, example.strip()))

Output:

hello...world...this...is...an...example
hello...world...this...is...an...example

split() without parameters splits over any amount of whitespace, and join takes the resulting iterable and joins the parts together with the replacement strings.

The second example shows how to substitute whitespace with the replacement strings using regular expressions, but it removes the whitespace on the outside with .strip(). The regular expression \s+ just means "whitespace characters, 1 or more, as many as possible" - which is what you want to replace.

Grismar
  • 27,561
  • 4
  • 31
  • 54