Advertisement

Python基础小练习_字符串2

阅读量:

Section1

复制代码
 输入一个字符串,打印所有奇数位上的字符(下标是1,3,5,7…位上的字符)。
    例如: 输入'abcd1234 '   输出'bd24'
    
    	s1 = 'abcd1234 '
    	print(s1[1::2])
    
    2. 输入用户名,判断用户名是否合法(用户名长度6~10位)。
    
    	user_name = input('输入用户名: ')
    	if 6 <= len(user_name) <= 10:
    	print('合法')
    	else:
    	print('不合法')
    
    3. 输入用户名,判断用户名是否合法(用户名中只能由数字和字母组成)。
    例如: **'abc'**  — 合法    **'123'** — 合法   **‘abc123a’**  — 合法
    
    	方法一:
    	user_name = input('输入用户名:')
    	for i in user_name:
    		if not (i.isdigit() or i.isupper() or i.islower()):
    			print(f'{user_name}不合法')
    	else:
    		print(f'{user_name}合法')
    
    	方法二:
    	user_name = input('输入用户名: ')
    	count = 0
    	for i in user_name:
    	if 'a' <= i <= 'z' or 'A' <= i <= 'Z' or '0' <= i <= '9':
        	count += 0
    	else:
        	count += 1
        	break
    	
    	if count == 0:
    	print('合法')
    	else:
    	print('不合法')
    
    4. 输入一个字符串,将字符串中所有的数字字符取出来产生一个新的字符串。
    例如:输入**'abc1shj23kls99+2kkk'**    输出:**'123992'**
    
    	s = 'abc1shj23kls99+2kkk'
    	for i in s:
    	if '0' <= i <= '9':
        	print(i, end='')
    
    5. 输入一个字符串,将字符串中所有的小写字母变成对应的大写字母输出  (用upper方法和自己写算法两种方式实现)。
    例如: 输入**'a2h2klm12+' **  输出 **'A2H2KLM12+'**
    
    	方法一:
    	s1 = 'a2h2klm12+'
    	s2 = s1.upper()
    	print(s2)
    
    	方法二:
    	s3 = 'a2h2klm12+'
    	s4 = ''
    	for i in s3:
    	if 'a' <= i <= 'z':
        	s4 += chr(ord(i) - 32)
    	else:
        	s4 += i
    	
    	print(s4)
    
    6. 输入一个小于1000的数字,产生对应的学号。
    例如: 输入**'23'**,输出**'py1901023'**    输入**'9'**, 输出**'py1901009'**     输入**'123'**,输出**'py1901123'**
    
    	s = input('输入数字:')
    	id = 'py1901%03d' % eval(s)
    	print(id)
    
    7. 输入一个字符串,统计字符串中非数字字母的字符的个数。
    例如: 输入**'anc2+93-sj胡说'**  输出:**4**     输入**'==='**   输出:**3**
    
    	s1 = 'anc2+93-sj胡说'
    	count = 0
    	for i in s1:
    	if not ('0' <= i <= '9' or 'a' <= i <= 'z' or 'A' <= i <= 'Z'):
        	count += 1
    	
    	print(count)
    
    8. 输入字符串,将字符串的开头和结尾变成'+',产生一个新的字符串。
    例如: 输入字符串**'abc123'**,  输出**'+bc12+'**
    
    	s1 = 'abc123'
    	new_str = '+' + s1[1:-1] + '+'
    	print(new_str)
    
    9. 输入字符串,获取字符串的中间字符。
    例如: 输入**'abc1234'**  输出:**'1'**     输入**'abc123'**  输出**'c1'**
    
    	s = input('输入字符串:')
    	mid_str = ''
    	if len(s) % 2 == 0:
    	mid_str += s[int(len(s) / 2 - 1):int(len(s) / 2+ 1)]
    	else:
    	mid_str += s[int(len(s) / 2)]
    	
    	print(mid_str)
    
    10. 写程序实现字符串函数find/index的功能(获取字符串1中字符串2第一次出现的位置)。
    例如: 字符串1为:**how are you? Im fine, Thank you!**  , 字符串2为:**you**,  打印**8**
    
    	s1 = 'how are you? Im fine, Thank you!'
    	s2 = input('输入字符串2:')
    	for i in range(len(s1)):
    	if s1[i:i+len(s2)] == s2:
        	print(i)
        	break
    else:
    	print('找不到')
    
    11. 获取两个字符串中公共的字符。
    例如: 字符串1为:**abc123**, 字符串2为: **huak3** , 打印:**公共字符有:a3**
    
    	s1 = 'abc123aaa'
    	s2 = 'huak3'
    	res = ''.join(set(s1) & set(s2))
    	print(res)
    
    12. 输入用户名,判断用户名是否合法(用户名必须包含且只能包含数字和字母,并且第一个字符必须是大写字母)。
    例如: **'abc'**  — 不合法  **'Mabc'** — 不合法   **'123'**  — 不合法   **'abc123'**  — 不合法    **'Abc123ahs'**  — 合法     
    
    	方法一:
    	user_name = 'Kfa2342'
    	if user_name[0].isupper():
    		num_count = 0
    		for i in user_name[1:]:
    			if not (i.isdigit() or i.isupper() or i.islower()):
    				print(f'{user_name}不合法')
    				break
    			elif i.isdigit():
    				num_count += 1
    		else:
    			if num_count == 0:
    				print(f'{user_name}不合法')
    			else:
    				print(f'{user_name}合法')
    	else:
    		print(f'{user_name}不合法')
    
    	方法二:
    	user_name = input('输入用户名:')
    	count1 = 0
    	count2 = 0
    	count3 = 0
    	if user_name[0].isupper():
    	for i in user_name[1:]:
        	if '0' <= i <= '9':
            	count1 += 1
        	elif 'a' <= i <= 'z' or 'A' <= i <= 'Z':
            	count2 += 1
        	else:
            	count3 += 1
            	break
    
    	if count1 != 0 and count2 != 0 and count3 == 0:
    	print('合法')
    	else:
    	print('不合法')

Section2

复制代码
 编写一个程序,交换指定字典的key和value。
    例如:dict1={'a':1, 'b':2, 'c':3}  -->  dict1={1:'a', 2:'b', 3:'c'}  
    
    	dict1={'a':1, 'b':2, 'c':3}
    	for i in dict1:
    	value = dict1.pop(i)
    	dict1[value] = i
    
    	print(dict1)
    
    2. 编写一个程序,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串。
    例如:传入'12a&bc12d-+'   -->  'abcd'
    
    	s = '12a&bc12d-+A'
    	new_s = ''
    	for i in s:
    	if 'a' <= i <= 'z' or 'A' <= i <= 'Z':
        	new_s += i
    
    	print(new_s)
    
    3. 写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母。
    例如: 'abc' -> 'Abc'   '12asd'  --> '12asd'
    
    	s = 'a324fw'
    	def new_capitalize(str1):
    	letter1 = str1[0].upper()
    	new_str1 = letter1 + str1[1:]
    	
    	return new_str1
    
    
    	new_capitalize(s)
    
    4. 写程序实现endswith的功能,判断一个字符串是否已指定的字符串结束。
    例如: 字符串1:'abc231ab' 字符串2:'ab' 函数结果为: True
     字符串1:'abc231ab' 字符串2:'ab1' 函数结果为: False
    
    	s1 = 'abc231ab'
    	s2 = 'abc'
    	def new_endswith(str1, str2):
    	length = len(str2)
    	if s1[-len(str2):] == str2:
        	return True
    	else:
        	return False
      
       
    	new_endswith(s1, s2)
    
    5. 写程序实现isdigit的功能,判断一个字符串是否是纯数字字符串。
    例如: '1234921'  结果: True
     '23函数'   结果: False
     'a2390'    结果: False
    
    	s = '1234921你'
    	def new_isdigit(str1):
    	count = 0
    	for i in str1:
        	if not '0' <= i <= '9':
            	count += 1
    	if count == 0:
        	return True
    	else:
        	return False
       
       
    	new_isdigit(s)
    
    6. 写程序实现upper的功能,将一个字符串中所有的小写字母变成大写字母。
    例如: 'abH23好rp1'   结果: 'ABH23好RP1'   
    
    	s = 'AabH23好rp1a'
    	def new_upper(str1):
    	new_s = ''
    	for i in str1:
        	if 'a' <= i <= 'z':
            	i = chr(ord(i) - 32)
            	new_s += i
        	else:
            	new_s += i
       
    		return new_s
    
       
    	new_upper(s)
    
    7. 写程序获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值。
    例如: 序列:[-7, -12, -1, -9]    结果: -1   
     序列:'abcdpzasdz'    结果: 'z'  
     序列:{'小明':90, '张三': 76, '路飞':30, '小花': 98}   结果: 98
    
    	obj = {'小明':90, '张三': 76, '路飞':30, '小花': 98}
    	def new_max(obj):
    	if type(obj) == dict:
        	new_obj = list(obj.values())
        	max_ele = max(new_obj)
    		else:
    		new_obj = list(obj)
    		max_ele = max(new_obj)
    		
    	return max_ele
    
       
    	new_max(obj)
    
    8. 写程序实现replace函数的功能,将指定字符串中指定的旧字符串转换成指定的新字符串。
    例如: 原字符串: 'how are you? and you?'   旧字符串: 'you'  新字符串:'me'  结果: 'how are me? and me?'
    
    	s1 = 'how are you? and you?'
    	s2 = 'you'
    	s3 = 'me'
    
    	方法一:
    	print(s3.join(s1.split(s2)))
    
    	方法二:
    	def new_replace(str1, str2, str3):
    	while str2 in str1:
        	index1 = str1.index(str2)
        	str1 = str1[:index1] + str3 + str1[index1 + len(str2):]
           
    	return str1
    
    
    	new_replace(s1, s2, s3)
    
    9. 写程序实现split的功能,将字符串中指定子串作为切割点对字符串进行切割。
    例如:原字符串: 'how are you? and you?'   切割点: 'you'  结果: ['how are ', '? and ', '?']
    
    	s1 = 'how are you? and you?'
    	s2 = 'you'
    	def new_split(str1, str2):
    	lst = []
    	new_s = str1
    	while str2 in str1:
        	index1 = str1.index(str2)
        	lst.append(str1[:index1])
        	str1 = str1[index1 + len(str2):]
    	
    	lst_pos = new_s.rindex(str2)
    		lst.append(new_s[lst_pos + len(str2):])
    
    		return lst
    
    
    	new_split(s1, s2)

全部评论 (0)

还没有任何评论哟~