取出字符串两边指定字符序列
str0 = "\nabc abc\n"
str1 = "123abcdefg123"
1.需求:切除str0字符串两边空格和换行 # abc abc
res=str0.split()
print(res)
2.需求:切除str1两边的“123”字符串 #abcefg
res=str1.strip("123")
print(res)
3.需求:切除str1左边或者右边的“123”内容分别是?
res1=str1.lstrip("123")
res2=str1.rstrip("123")
print(res1,res2,sep=",")
转换方法
1.将字符串中的大写字母转换为小写字母
str0 = "aHello good"
res = str0.lower()
print(res)
2.将小写字母转为大写字母
res = str0.upper()
print(res)
3.将大写转为小写 小写转为大写
res = str0.swapcase()
print(res)
4.第一字母大写 其余全小写
res = str0.capitalize()
print(res)
5.将每个单词的首字母大写 其余的都是小写【单词和单词直接由空格隔开】
res = str0.title()
print(res)
案例:键盘录入年和月,要求输出对应月份的天数【平年和闰年】
time = input("请输入年月(例:200906):")
year = time[:4]
month = time[4:6]
print(year+"年",month+"月")
list1 = [1,3,5,7,8,10,12]
# list2 = [4,6,9,11]
if year%4 ==0:
if month == 2:
print(29)
elif (month in list1):
print(31)
else:
print(30)
else:
if month == 2:
print(28)
elif (month in list1):
print(31)
else:
print(30)
if year%4==0 and month==2 :
print(29)
elif year%4==0 and month != 2:
print(28)
elif year%4 != 0 and (month in list1):
print(31)
elif year%4 != 0 and (month in list2):
print(30)
else:
print("请重新输入!")
&
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
if month >= 1 and month <= 12:
if month in (1, 3, 5, 7, 8, 10, 12):
day = 31
elif month in (4, 6, 9, 11):
day = 30
else:
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
day = 29
else:
day = 28
print("%d年%d月有%d天" % (year, month, day))
else:
print("月份输入有误!")