示例 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 程序