Search code examples
pythonpython-2.7python-3.xwhitespacespaces

Count the number of spaces between words in a string


I am doing this problem on Hackerrank,and I came up with the idea, which includes splitting the input and join it afterwards (see my implementation below). However, one of the test cases contains the input (hello< multiple spaces> world), which crashed my code because the input string has more than 1 space between each words. So, I am just wondering if anyone could please help me out fix my code, and I am just wondering how to count how many spaces(esp multiple spaces) in a string in Python. I found how to count spaces in Java, but not in Python. For testcase, I attached the pic.

Thanks in advance.

My implementation:

input_string = input()

splitter = input_string.split()

final = []

for i in range(0,len(splitter)):
    for j in range(0,len(splitter[i])):
        if(j==0):
            final.append(splitter[i][j].upper())
        else:
            final.append(splitter[i][j])
    # Assumed that there is one space btw each words
    final.append(' ')
print(''.join(final))

For Test case pic,

enter image description here


Solution

  • You can fix it by splitting with pattern ' ' (whitespace)

    splitter = input_string.split(' ')
    

    You can also use .capitalize() method instead of splitting the token again

    s = "hello  world         4lol"
    a = s.split(' ')
    
    new_string = ''
    for i in range(0, len(a)) :
       new_string = a[i].capitalize() if len(new_string)==0 else new_string +' '+ a[i].capitalize()
    print(new_string)
    

    Output:

    Hello  World         4lol
    

    For counting number of spaces between two words, you can use python's regular expressions module.

    import re    
    s = "hello       world  loL"
    tokens = re.findall('\s+', s)
    
    for i in range(0, len(tokens)) :
        print(len(tokens[i]))
    

    Output :

    7
    2