简体   繁体   中英

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,

在此处输入图像描述

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

What I suggest doing for the tutorial question is a quick simple solution.

s = input()
print(s.title())

str.title() will capitalise the starting letter of every word in a string.


Now to answer the question for counting spaces you can use str.count()) which will take a string and return the number of occurrences it finds.

s = 'Hello    World'
s.count(' ')

There are various other methods as well, such as:

s = input()
print(len(s) - len(''.join(s.split())))

s2 = input()
print(len(s2) - len(s2.replace(' ', '')))

However count is easiest to implement and follow.

Now, count will return the total number, if you're after the number of spaces between each world.

Then something like this should suffice

s = input()

spaces = []
counter = 0
for char in s:
    if char== ' ':
        counter += 1
    elif counter != 0:
        spaces.append(counter)
        counter = 0

print(spaces)
import re    
line = "Hello    World  LoL"
total = 0
for spl in re.findall('\s+', line):
    print len(spl)
    total += len(spl) # 4, 2
print total # 6

>>> 4
>>> 2
>>> 6

For you problem with spaces

my_string = "hello    world"
spaces = 0
for elem in my_string:
    if elem == " ":
    #space between quotes
    spaces += 1
print(spaces)

you can use count() function to count repeat of a special character

string_name.count('character')

for count space you should:

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])
    final.append(' ')
count = input_string.count(' ')
print(''.join(final))
print (count)

good luck

Forget the spaces they are not your problem.
You can reduce the string to just the words without the extra spaces using split(None) which will give you a word count and your string ie

>>> a = "   hello  world         lol"
>>> b = a.split(None)
>>> len(b)
3
>>> print(" ".join(b))
hello world lol

Edit: After following your link to read the actual question, next time include the relevant details in your question, it makes it easier all round, your issue still isn't counting the number of spaces, before, between or after the words. The answer that solves the specific task has already been provided, in the form of:

>>> a= " hello    world  42  lol"
>>> a.title()
' Hello    World  42  Lol'
>>> 

See the answer provided by @Steven Summers

I solved that problem a time ago, just add " " (white space) to the split function and then print each element separated by a white space. Thats all.

for i in input().split(" "):
    print(i.capitalize(), end=" ")

The result of the split function with "hello world lol" is

>>> "hello    world    lol".split(" ")
>>>['hello', '', '', '', 'world', '', '', '', 'lol']

Then print each element + a white space.

Approach


Given a string, the task is to count the number of spaces between words in a string.

Example:

Input: "my name  is geeks for geeks"
Output: Spaces b/w "my" and "name": 1
        Spaces b/w "name" and "is": 2
        Spaces b/w "is" and "geeks": 1
        Spaces b/w "geeks" and "for": 1
        Spaces b/w "for" and "geeks": 1

Input: "heyall"
Output: No spaces

Steps to be performed


  • Input string from the user's and strip the string for the removing unused spaces.
  • Initialize an empty list
  • Run a for loop from 0 till the length of the string
  • Inside for loop, store all the words without spaces
  • Again Inside for loop, for storing the actual Indexes of the words.
  • Outside for loop, print the number of spaces b/w words.

Below is the implementation of the above approach:

# Function to find spaces b/w each words
def Spaces(Test_string):
    Test_list = []  # Empty list
    
    # Remove all the spaces and append them in a list
    for i in range(len(Test_string)):
        if Test_string[i] != "":
            Test_list.append(Test_string[i])
            
    Test_list1=Test_list[:]
    
    # Append the exact position of the words in a Test_String
    for j in range(len(Test_list)):
        Test_list[j] = Test_string.index(Test_list[j])
        Test_string[j] = None
        
    # Finally loop for printing the spaces b/w each words.
    for i in range(len(Test_list)):
        if i+1 < len(Test_list):
            print(
                f"Spaces b/w \"{Test_list1[i]}\" and \"{Test_list1[i+1]}\": {Test_list[i+1]-Test_list[i]}")

# Driver function
if __name__ == "__main__":
    Test_string = input("Enter a String: ").strip() # Taking string as input
    
    Test_string = Test_string.split(" ")  # Create string into list
    
    if len(Test_string)==1:
        print("No Spaces")
    else:
        Spaces(Test_string)  # Call function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM