第11-第20个python练习

11.判断一个字符串是否为数字(包括整数和小数)

defis_number(string):
    try:
        float(string)
        returnTrueexceptValueError:
        returnFalsemy_str = "123.45"ifis_number(my_str):
    print("{0} 是数字".format(my_str))
else:
    print("{0} 不是数字".format(my_str))

12.计算列表元素之和


defsum_of_list(lst):
sum=0foriteminlst:
sum+=item
returnsumlst=[1,2,3,4,5]
print("列表:",lst)
print("列表元素之和为:",sum_of_list(lst))

13.将字符串反转输出


defreverse_string(string):
returnstring[::-1]

my_str="HelloWorld"print("原始字符串:",my_str)
print("反转后的字符串:",reverse_string(my_str))

14.统计字符串中某个字符出现的次数


defcount_char(string,char):
count=0forcinstring:
ifc==char:
count+=1returncountmy_str="HelloWorld"char="l"print("{0}出现的次数为:{1}".format(char,count_char(my_str,char)))

15.求两个列表的交集


defintersection(lst1,lst2):
returnlist(set(lst1)&set(lst2))

lst1=[1,2,3,4,5]
lst2=[4,5,6,7,8]
print("列表1:",lst1)
print("列表2:",lst2)
print("它们的交集为:",intersection(lst1,lst2))

16.求两个列表的并集


defunion(lst1,lst2):
returnlist(set(lst1)|set(lst2))

lst1=[1,2,3,4,5]
lst2=[4,5,6,7,8]
print("列表1:",lst1)
print("列表2:",lst2)
print("它们的并集为:",union(lst1,lst2))

17.将列表中的元素向左移动n位

defleft_rotate(lst,n):
returnlst[n:]+lst[:n]

lst=[1,2,3,4,5]
n=2print("列表:",lst)
print("向左移动{0}位后的列表:".format(n),left_rotate(lst,n))

18.判断一个字符串是否为数字

defis_number(string):
try:
float(string)
returnTrueexceptValueError:
passtry:
importunicodedata
unicodedata.numeric(string)
returnTrueexcept(TypeError,ValueError):
passreturnFalsestring_1="1234"string_2="12.34"string_3="一二三四"print("{0}是否为数字:{1}".format(string_1,is_number(string_1)))
print("{0}是否为数字:{1}".format(string_2,is_number(string_2)))
print("{0}是否为数字:{1}".format(string_3,is_number(string_3)))

19.将字符串转换为驼峰命名法

defto_camel_case(string):
words=string.split("_")
returnwords[0]+"".join([word.capitalize()forwordinwords[1:]])

my_str="hello_world"print("原始字符串:",my_str)
print("转换后的字符串:",to_camel_case(my_str))

20.计算兔子总数

deffibonacci(n):
ifn<=0:
return0elifn==1:
return1else:
returnfibonacci(n-1)+fibonacci(n-2)

month=int(input("请输入月份:"))
print("兔子总数为:",fibonacci(month+1))
posted on 2023-03-28 10:04  skywide  阅读(10)  评论(0)    收藏  举报  来源