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.

Lauren Yim
  • 12,700
  • 2
  • 32
  • 59
BBG_GIS
  • 306
  • 5
  • 17

4 Answers4

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
deadshot
  • 8,881
  • 4
  • 20
  • 39
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')
JaniniRami
  • 493
  • 3
  • 11
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
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30
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
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50