2016-11-24 49 views
0

如果字符串中的字符是特殊字符(例如#。@。$),是否有一個特定的函數返回true?比如,如果字符串中的所有字符都是字母,則isalpha()函數返回true。Python字符串處理函數

我必須創建一個程序,我需要向用戶詢問一個字符串,然後我的程序必須打印字符串的長度,字母數量,數字位數以及不是字母的字符數。

counter = 0 
num = 0 
extra = 0 

wrd = raw_input("Please enter a short sentence.") 

for i in wrd: 
    if i.isalpha(): 
     counter = counter + 1 

print "You have " + str(counter) +" letters in your sentence." 

for n in wrd: 
    if n.isnumeric(): 
     num = num + 1 

print "You have " + str(num) + " number(s) in your sentence" 

for l in wrd: 
    extra = extra + 1 

print "You have " + str(extra) + " characters that are not letters or numbers." 

我拿到了前兩個部分想通了,雖然我卡上的最後一個...我知道它的容易,只需創建一個while循環,但是,因爲我已經開始了,我要堅持三個四個環。

+1

爲什麼不'len(wrd) - counter - num'? – TigerhawkT3

回答

3

你不需要另一個功能。既然你已經計入其他人物,從總減去他們:

print "You have", len(wrd) - counter - num, "characters that are not letters or numbers." 
0

是否存在,如果字符串中的字符是特殊字符,則返回true特定功能(例如:#@ $) ?比如,如果字符串中的所有字符都是字母,則isalpha()函數返回true。

沒有,但它很容易創建自己:

import string 

def has_special_chars(s): 
    return any(c in s for c in string.punctuation) 

測試:

>>> has_special_chars("[email protected]$dujhf&") 
True 
>>> has_special_chars("abtjhjfdujhf") 
False 
>>> 

在你的情況,你會使用它想:

for l in wrd: 
    if has_special_chars(l) 
     extra=extra+1 

但是@ TigerHawkT3已經打敗了我說,你應該簡單地使用len(wrd) - counter - num來代替。它是最經典和最明顯的方式。

0

只需登錄一個通用的答案是將應用超出了這個範圍內 -

import string 
def num_special_char(word): 
    count=0 
    for i in word: 
     if i in string.punctuation: 
      count+=1 
    return count 

print "You have " + str(num_special_char('Vi$vek!')) + " characters that are not letters or numbers." 

輸出

You have 2 characters that are not letters or numbers. 
0

使用一個for循環與ifelifelse

sentence = raw_input("Please enter a short sentence.") 

alpha = num = extra = 0 
for character in sentence: 
    if character.isspace(): 
     pass 
    elif character.isalpha(): 
     alpha += 1 
    elif character.isnumeric(): 
     num += 1 
    else: 
     extra += 1 

print "You have {} letters in your sentence.".format(alpha) 
print "You have {} number(s) in your sentence".format(num) 
print "You have {} characters that are not letters or numbers.".format(extra)