2016-11-24 52 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)