Skip to content

Instantly share code, notes, and snippets.

@bbookman
Created December 26, 2018 21:42
Show Gist options
  • Save bbookman/f0d36dfee6f6b3aa861fb026f1d5eb83 to your computer and use it in GitHub Desktop.
Save bbookman/f0d36dfee6f6b3aa861fb026f1d5eb83 to your computer and use it in GitHub Desktop.
Python List Comprehension: Count the number of spaces in a string
'''
Count the number of spaces in a string
'''
some_string = 'the slow solid squid swam sumptuously through the slimy swamp'
spaces = [s for s in some_string if s == ' ']
print(len(spaces))
@ashkanhasani
Copy link

I try it:
list1 = [x for x in str1 if x.isspace()]

@stanohachu
Copy link

[i for i in some_string].count(' ')

@Amine-Fadssi
Copy link

len([letter for letter in some_string if letter == ' '])

@pawlinski
Copy link

print(some_string.count(" "))

@Kacjan
Copy link

Kacjan commented Apr 23, 2024

Is this still list comprehension without [i for i ...] format?
But if the result we want to get is a list with a number of spaces in the string this code should be fine:

space_find = [some_string.count(' ')]
print(space_find)

@shaik23032001
Copy link

l=sum([1 for i in range(len(s))if s[i]==' '])

@shaik23032001
Copy link

Is this still list comprehension without [i for i ...] format? But if the result we want to get is a list with a number of spaces in the string this code should be fine:

space_find = [some_string.count(' ')] print(space_find)

here you are not using list comprehension

@Christian-Stefan
Copy link

the_number_of_white_Spaces_in_any_string = [input(str('Waiting for a sentence...')).count(' ')]

@RBub
Copy link

RBub commented Jun 16, 2024

res = sum([1 for x in s if x == ' '])

@EureAkash
Copy link

I have a doubt here, if some_string.count(' ') could already give the number of white spaces available with a simple line.
Then do we need List Comprehension ?
which one is more efficient

@vgauss07
Copy link

vgauss07 commented Aug 9, 2024

spaces = " "
num_of_space = [len(space) for space in spaces if space == " "]
print(num_of_space)

@RudraPatel5435
Copy link

l = some_string.count(" ")
print(l)

@RudraPatel5435
Copy link

l = some_string.split()
print(len(l) - 1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment