Python中如何判断一个字符串中有几个空格

2025-06-22 04:35:12
推荐回答(2个)
回答1:

a='2014.11  2016.03  xxx'
print len(a) - len(a.replace(' ','')) ,'个空格'

回答2:

#!/usr/bin/env python
# coding=utf-8

"""
Python中如何判断一个字符串中有几个空格
http://zhidao.baidu.com/question/138854675106454205.html
"""

from __future__ import (print_function, unicode_literals)

text = '2014.11  2016.03  xxx有限公司  (1年4个月)'

currentCharIsSpace = False
count = 0
for c in text:
    if currentCharIsSpace:
        if c.isspace():
            count += 1
        else:
            currentCharIsSpace = False
            print(" %s个空格" % (count,))
    else:
        if c.isspace():
            count = 1
            currentCharIsSpace = True
        else:
            print(c, end="")

if currentCharIsSpace:
    currentCharIsSpace = False
    print(" %s个空格" % (count,))

运行结果

2014.11 2个空格
016.03 2个空格
xx有限公司 2个空格
1年4个月)