day9-字符串作业
輸入一個字符串,打印所有奇數位上的字符(下標是1,3,5,7…位上的字符)
例如: 輸入**'abcd1234 ’ ** 輸出**‘bd24’**
str1 = 'abcd1234 ' new_str1 = '' # str2 = input('請輸入一個字符串:') for x in str1[1::2]:new_str1 += x print(new_str1) 結果:bd24輸入用戶名,判斷用戶名是否合法(用戶名長度6~10位)
str2 = input('請輸入一個用戶名:') if 6 <= len(str2) <= 10:print('用戶名合法') else:print('用戶名不合法')結果:請輸入一個用戶名:陳來用戶名不合法**輸入用戶名,判斷用戶名是否合法(用戶名中只能由數字和字母組成)
例如: ‘abc’ — 合法 ‘123’ — 合法 ‘abc123a’ — 合法
str2 = input('請輸入一個用戶名:') for x in str2:if not ('0' <= x <= '9' or 'a' <= x <= 'z' or 'A' <= x <= 'Z'):print('用戶名不合法')break else:print('用戶名合法')結果:請輸入一個用戶名:abc123用戶名合法輸入用戶名,判斷用戶名是否合法(用戶名必須包含且只能包含數字和字母,并且第一個字符必須是大寫字母)
例如: ‘abc’ — 不合法 ‘123’ — 不合法 ‘abc123’ — 不合法 ‘Abc123ahs’ — 合法
str2 = input('請輸入一個用戶名:') if 'A' <= str2[0] <= 'Z':for x in str2[1:]:if not ('0' <= x <= '9' or 'a' <= x <= 'z' or 'A' <= x <= 'Z'):print('用戶名不合法')breakelse:print('用戶名合法') else:print('用戶名不合法')結果:請輸入一個用戶名: **'abc123'** 用戶名不合法輸入一個字符串,將字符串中所有的數字字符取出來產生一個新的字符串
例如:輸入**‘abc1shj23kls99+2kkk’** 輸出:'123992’
str3 = 'abc1shj23kls99+2kkk' new_str3 = '' for x in str3:if '0' <= x <= '9':new_str3 += x print(new_str3) #123992 結果:123992輸入一個字符串,將字符串中所有的小寫字母變成對應的大寫字母輸出 (用upper方法和自己寫算法兩種方式實現)
例如: 輸入**‘a2h2klm12+’ ** 輸出 'A2H2KLM12+'
#方法一
str2 = 'a2h2klm12+' print(str2.upper()) # A2H2KLM12+方法二**:
str2 = 'a2h2klm12+' new_str2 = '' for y in str2:if 'a' <= y <= 'z':new_str2 += chr(ord(y)-32)else:new_str2 += y # 加else print(new_str2) # A2H2KLM12+*輸入一個小于1000的數字,產生對應的學號
例如: 輸入**‘23’,輸出’py1901023’** 輸入**‘9’, 輸出’py1901009’** 輸入**‘123’,輸出’py1901123’**
str1 = input('請輸入一個小于1000的數字:') str2 = 'py1901000' if len(str1) == 1:new_str2 = str2[0:-1]+str1 elif len(str1) == 2:new_str2 = str2[0:-2]+str1 elif len(str1) == 3:new_str2 = str2[0:-3]+str1 print(new_str2) 結果: 請輸入一個小于1000的數字:999 py1901999輸入一個字符串,統計字符串中非數字字母的字符的個數
例如: 輸入**‘anc2+93-sj胡說’** 輸出:4 輸入**’===’** 輸出:3
str1 = input('請輸入一個字符串:') count = 0 for x in str1:if not ('0' <= x <= '9' or 'a' <= x <= 'z' or 'A' <= x <= 'Z'):count += 1 print(count) 結果: 請輸入一個字符串:anc2+93-sj胡說 4輸入字符串,將字符串的開頭和結尾變成’+’,產生一個新的字符串
例如: 輸入字符串**‘abc123’, 輸出’+bc12+’**
str1 = input('請輸入一個字符串:') new_str1 = '+'+str1+'+' print(new_str1) 結果: 請輸入一個字符串:abc123 +abc123+***輸入字符串,獲取字符串的中間字符
例如: 輸入**‘abc1234’** 輸出:‘1’ 輸入**‘abc123’** 輸出**‘c1’**
str1 = 'abc123' len1 = len(str1) if len1 % 2: # 注意%的用法x = (len1 // 2)print(str1[x]) else:x = (len1//2) - 1y = len1//2print(str1[x], str1[y])結果:c 1例如: 字符串1為:how are you? Im fine, Thank you! , 字符串2為:you, 打印8
str1 = 'how are you? Im fine, Thank you!' str2 = 'you' if str2 in str1:for x, y in enumerate(str1):if str2[0] == str1[x]:print('字符串1中字符串2第一次出現的位置:',x)break 結果: 字符串1中字符串2第一次出現的位置: 8例如: 字符串1為:abc123, 字符串2為: huak3 , 打印:公共字符有:a3
str1 = 'abc123' str2 = 'huak3' str3 = '' for x in str1:if x in str2:str3 += x print(str3) 結果: a3?
總結
以上是生活随笔為你收集整理的day9-字符串作业的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java常用时间工具类
- 下一篇: android定位方式