I've already managed to remove the space at the beginning and end of the string with the function strip () but I do not know how to eliminate when in the text there are more than two spaces between words
for example:
a = ' this is the test '
a = a.split()
print a
'this is the test'
What kind of example is this?
Quote:Signature: str.split(self, /, sep=None, maxsplit=-1)
Docstring:
Return a list of the words in the string, using sep as the delimiter string.
sep
The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
Type: method_descriptor
So You can't have string after using split() method. You get list.
>>> a = 'this is a test'
>>> a.split()
['this', 'is', 'a', 'test']
(Mar-29-2019, 02:19 PM)perfringo Wrote: [ -> ]What kind of example is this?
Quote:Signature: str.split(self, /, sep=None, maxsplit=-1)
Docstring:
Return a list of the words in the string, using sep as the delimiter string.
sep
The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
Type: method_descriptor
So You can't have string after using split() method. You get list.
>>> a = 'this is a test'
>>> a.split()
['this', 'is', 'a', 'test']
sorry I was wrong to write it's a.sprit()
Just spaces? What about newlines or tabs?
If you only care about spaces, a simple while loop would work, using
str.replace
repeatedly:
>>> a = ' this is the test '
>>> temp = None
>>> while a != temp or temp is None:
... if temp is not None:
... a = temp
... temp = a.replace(" ", " ")
...
>>> a
' this is the test '
Or, if you want a "better" way, use a regex so it's just a single-pass through the string:
>>> import re
>>> a = ' this is the test '
>>> regex = re.compile(" {2,}")
>>> regex.sub(" ", a)
' this is the test '
Or, if you don't care about maintaining leading/trailing whitespace, you could continue to extend the
str.split()
you were using:
>>> a = ' this is the test '
>>> ' '.join(a.split())
'this is the test'
You can use a counter. If you don't want multiple print statements per line of input. put the code in a function and return on the first greater-than-2-spaces found. Also you can use a.find(" ") <-- is actually 3 spaces, but that may not be specific enough.
str_ctr=0
a = ' this is the test '
for ltr in a:
if ltr == " ":
str_ctr += 1
if str_ctr > 2:
print("Too many spaces", a)
else:
str_ctr = 0