如何让Python忽略额外的空格?

时间:2017-04-24 01:15:18

标签: python function loops

我有一个编写代码来分配字符串中的单词的作业。我还没学会分裂,所以我不能用它。我只能使用函数,循环和条件。他故意在一个字符串中添加了三个额外的空格,我必须弄清楚如何将它作为一个来处理它。我被卡住了。救命啊!

def wordCount(myString):
    try:
        spaceCount = 0
        char = ""
        for i in myString:
            char += i
            if char == "  ":
                spaceCount == 1
                pass
            elif char == " ":
                spaceCount += 1
        return spaceCount+1
    except:
        return "Not a string"

print("Word Count:", wordCount("Four words are here!"))
print("Word Count:", wordCount("Hi   David"))
print("Word Count:", wordCount(5))
print("Word Count:", wordCount(5.1))
print("Word Count:", wordCount(True))

2 个答案:

答案 0 :(得分:1)

这种作品:

def wordCount(myString):
    try:
        words = 0
        word = ''
        for l in myString : 
            if ( l == ' ' and word != '' ) or ( l == myString[-1] and l != ' ' ) : 
                words += 1
                word = ''
            elif l != ' ' : 
                word += l
        return words
    except Exception as ex :
        return "Not a string"

print("Word Count:", wordCount("Four words are here!"))
print("Word Count:", wordCount("Hi   David"))
print("Word Count:", wordCount(5))
print("Word Count:", wordCount(5.1))
print("Word Count:", wordCount(True))

结果:

'Word Count:', 4
'Word Count:', 2
'Word Count:', 'Not a string'
'Word Count:', 'Not a string'
'Word Count:', 'Not a string'

答案 1 :(得分:0)

def wordCount(s):
    try:
        s=s.strip()
        count = 1 
        for i,v in enumerate(s):
            #scan your string in pair of 2 chars. If there's only one leading space, add word count by 1.
            if (len(s[i:i+2]) - len(s[i:i+2].lstrip()) == 1):
                count+=1
        return count
    except:
        return "Not a string"
print("Word Count:", wordCount("Four words are here!  "))
print("Word Count:", wordCount("Hi   David"))
print("Word Count:", wordCount(5))
print("Word Count:", wordCount(5.1))
print("Word Count:", wordCount(True))
相关问题