Python 简明教程
Python - String Exercises
Example 1
查找给定字符串中元音数量的 Python 程序。
mystr = "All animals are equal. Some are more equal"
vowels = "aeiou"
count=0
for x in mystr:
if x.lower() in vowels: count+=1
print ("Number of Vowels:", count)
它将生成以下 output −
Number of Vowels: 18
Example 2
将二进制位字符串转换为整数的 Python 程序。
mystr = '10101'
def strtoint(mystr):
for x in mystr:
if x not in '01': return "Error. String with non-binary characters"
num = int(mystr, 2)
return num
print ("binary:{} integer: {}".format(mystr,strtoint(mystr)))
它将生成以下 output −
binary:10101 integer: 21
将 mystr 更改为 '10, 101'
binary:10,101 integer: Error. String with non-binary characters