Python - 弦乐练习


实施例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)

它将产生以下输出-

Number of Vowels: 18

实施例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)))

它将产生以下输出-

binary:10101 integer: 21

将mystr更改为 '10, 101'

binary:10,101 integer: Error. String with non-binary characters

实施例3

Python 程序删除字符串中的所有数字。

digits = [str(x) for x in range(10)]
mystr = 'He12llo, Py00th55on!'
chars = []
for x in mystr:
   if x not in digits:
      chars.append(x)
newstr = ''.join(chars)
print (newstr)

它将产生以下输出-

Hello, Python!

锻炼计划

  • Python程序对字符串中的字符进行排序

  • Python程序从字符串中删除重复字符

  • Python 程序列出字符串中的唯一字符及其计数

  • Python程序查找字符串中的单词数

  • Python程序从字符串中删除所有非字母字符