Reputation: 45
How do you detect if there are 2 consecutive spaces in a string in Python?
For example, with the input string:
Hello there
I'd like to detect the two spaces and return True
.
I know you can use split
and join
to fill in the consecutive spaces, but how do you detect them?
Upvotes: 1
Views: 228
Reputation: 838076
If you want to find two or more consecutive spaces:
if " " in s:
# s contains two or more consecutive space
If you want to find two or more spaces anywhere in the string:
if s.count(' ') >= 2:
# s contains two or more spaces
Upvotes: 7
Reputation: 235994
A more general solution is achieved by using regular expressions, for checking if there are two or more consecutive spaces anywhere in the input string. For instance:
import re
if re.search('\s{2,}', s):
# s contains two or more consecutive spaces
If you only need to check if there are exactly two spaces anywhere in the string, you're better off using @Mark Byers 's solution, as is simpler.
Upvotes: 2