How to count the white spaces in a string in Python

2 Answers

0 votes
def count_whitespaces_in_string(s):
    whitespaces = len(s) - len(s.lower().replace(" ", "").replace("\n", "").replace("\r", "").replace("\t", ""))
    
    return whitespaces
    
s = "Python \n  Programming \r Language \t ";

print("Total white spaces:", count_whitespaces_in_string(s))


'''
run:

Total white spaces: 10

'''

 



answered Oct 19, 2024 by avibootz
0 votes
def count_whitespaces_in_string(s):
    return sum(1 for c in s if c.isspace())

s = "Python \n  Programming \r Language \t ";

print("Total white spaces:", count_whitespaces_in_string(s))


'''
run:

Total white spaces: 10

'''

 



answered Oct 19, 2024 by avibootz

Related questions

1 answer 110 views
1 answer 121 views
1 answer 106 views
1 answer 89 views
1 answer 106 views
1 answer 77 views
1 answer 73 views
...