Let's say I have a string like s = 'This string has double spaces or more in it.\n What to do'
I would like to split it so it becomes ['This', 'string has', 'double spaces', 'or', 'more', 'in', 'it.\n', 'What', 'to', 'do']
How can I ignore multiple spaces and split them as one word?
regex - Split string on whitespace in Python - Stack Overflow
string - How can I split by 1 or more occurrences of a delimiter in Python? - Stack Overflow
python - What happens if we split by a delimiter yet have multiple of those delimiters in a row? - Stack Overflow
How to consider multiple spaces as single in python?
str.split(" ") gives you multiple empty values. Use str.split(None) or just str.split() instead; it'll collapse arbitrary-width whitespace into one split position:
>>> 'demo with multiple spaces'.split(' ')
['demo', '', 'with', '', '', 'multiple', '', '', '', 'spaces']
>>> 'demo with multiple spaces'.split()
['demo', 'with', 'multiple', 'spaces']
The None or no argument version also removes leading and trailing whitespace, including tabs and newlines:
>>> '\tdemo with some leading \t and trailing whitespace\n'.split()
['demo', 'with', 'some', 'leading', 'and', 'trailing', 'whitespace']
while str.split(' ') splits only on spaces:
>>> '\tdemo with some leading \t and trailing whitespace\n'.split(' ')
['\tdemo', 'with', 'some', 'leading', '', '\t', 'and', 'trailing', 'whitespace\n']
If there is an arbitrary amount of whitespace between each one, split() without arguments will work just fine:
>>> 'foo bar baz quz'.split()
['foo', 'bar', 'baz', 'qux']
split() by defaults to all whitespace as the delimiter. If you specify a single space ' ', that is all it will split on and you will get empty strings as a result.
def count_words(s):
if s == '':
return None
else:
count=1
for i in s:
if i == ' ':
count+=1
return count
s=input()
print(count_words(s))The code in the upwards from actually counts the words in a string and returns a number. However, it actually counts the spaces and I naturally assumed that there would be a single space between each word in a sentence, but I wanted to extend this code even further. The string should only return the number of words if there are any number of spaces there. How do I exclude more than One space or suggest me a better solution.