程序练习1:
#编写一个函数,分别统计传入字符串参数(可能不止一个参数)的英文字母、
空格、数字和其他字符的个数
# 程序执行结果举例:
# count('i love you','i love you ,you love test123.com')
# 第一个字符串共有:英文字母8个,数字0个,空格2个,其他字符0个。
# 第二个字符串共有:英文字母14个,数字3个,空格2个,其他字符2个。
程序练习2:
# 编写一个函数,判断输入的字符串参数是否为回文联。
# 回文联即用回文形式携程的对联,既可顺读,也可逆读。比如:上海自来水来自海上
习题1参考答案:
def count(*param):
length=len(param)
for i in range(length):
letters=0
space=0
digit=0
others=0
for each in param[i]:
if each.isalpha():
letters+=1
elif each.isdigit():
digit+=1
elif each==' ':
space+=1
else:
others+=1
print('第 %d 个字符串共有:英文字母 %d 个,数字 %d 个,空格 %d个,其他字符 %d 个' %(i+1,letters,digit,space,others))
count('i love you','i love you ,you love test123.com')
习题2参考答案:
#方法1
def huiwen(x):
length=len(x)
lx=list(x)
ishw='Y'
for each in range(length):
if lx[each]!=lx[length-each-1]:
ishw='N'
break
if ishw=='Y':
print("是回文联")
else:
print("不是回文联")
#方法2
def huiwen2(x):
length=len(x)
ishw='Y'
for each in range(length):
if x[each]!=x[length-each-1]:
ishw='N'
break
if ishw=='Y':
print("是回文联")
else:
print("不是回文联")
#方法3
#Python 有两种除法操作符,
# 一种是单斜杠:用于传统除法,
# 另一种双斜杠:用于浮点数除法,其结果进行四舍五入。
def huiwen3(x):
length=len(x)
last=length-1 #最后一位
length//=2
ishw='Y'
for each in range(length):
if x[each]!=x[last]:
ishw='N'
break
last-=1
if ishw=='Y':
print("是回文联")
else:
print("不是回文联")
#方法4
def huiwen4(x):
lx=list(x)
lxr=reversed(lx)
#print(lxr)
if lx==list(lxr):
print("是回文联")
else:
print("不是回文联")
temp=input("请输入要判断的字符串: ")
huiwen(temp)
huiwen2(temp)
huiwen3(temp)
huiwen4(temp)
往期笔记