1

I want to find multiple spaces in a string using python. How to check if multiple spaces exist in a string?

mystring = 'this   is a test'

I have tried the below code but it does not work.

if bool(re.search(' +', ' ', mystring))==True:
    # ....

The result must return True.

3
  • Can you elaborate more on your question? Also, can you post what you've tried so far? Commented Aug 31, 2020 at 7:09
  • 3
    did you mean to say "multiple consecutive spaces"? Commented Aug 31, 2020 at 7:12
  • 1
    Does this answer your question? Python - Check multiple white spaces in string Commented Aug 31, 2020 at 7:12

4 Answers 4

2

You can use split() if you give no delimiter it will consider space as delimiter. after split check the length.If the length is greater than one it has spaces.

mystring = 'this   is a test'

if len(mystring.split()) > 1:
    #do something
Sign up to request clarification or add additional context in comments.

1 Comment

OP want to find multiple spaces in a string. len(mystring.split()) is > 1 even if mystring contains single spaces
1

You can use the string.count() method: If you want to check if multiple (more than one and no matter what their length) spaces exist the code is:

mystring.count(' ')>1

If you want to check if there is at least one consecutive space the code is:

mystring.count('  ')>=1

1 Comment

if that's what you want, just use in
1

You can use re and compare the strings like this:

import re

mystring = 'this  is a test'
new_str = re.sub(' +', ' ', mystring)


if mystring == new_str:
    print('There are no multiple spaces')
else:
    print('There are multiple spaces')

Comments

0

The syntax you use for re.search is wrong. It should be re.search(pattern, string, flags=0).

So, you can just do, searching for 2 or more spaces:

import re

def contains_multiple_spaces(s):
    return bool(re.search(r' {2,}', s))

contains_multiple_spaces('no multiple spaces')
# False

contains_multiple_spaces('here   are multiple spaces')
# True

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.