[综合练习题]Python3 字符串,元组,列表,字典练习题

1. 字符串连接

定义字符串变量

1.请定义三个字符串a,b,c值分别为 I,like, python

2.请将上面三个变量合并输出 ‘I like python’

a='i'
b='like'
c='python'
print(a,b,c)

2. 字符串函数

定义一个变量 s= ‘ sdghHhf ‘

1.请先将变量s的空白符去掉 赋值给新变量s1 打印输出

s = ' sdghHhf '
s1=s.strip()
print(s1)

3. 字符串函数

请分别将s1变为全部大写(命名s2),小写(命名s3),打印输出s2,s3

s = ' sdghHhf '
s1=s.strip()
s2=s1.upper()
s3=s1.lower()
print(s2,s3)

4. 字符串函数

请查找s1中h最先出现的位置 赋值给s4 打印输出

s = ' sdghHhf '
s1=s.strip()
s4=s1.find('h')
print(s4)

5. 字符串函数

定义一个变量x=’I {} pyhon’

请用两种方法将x中的字符串{}修改为 like 并分别赋值给两个变量x1,x2 打印输出

x='I {} pyhon'
x1='I {} python'.format('like')
x2=x.replace('{}','like')
print(x1,x2)

6. 字符串函数

定义一个变量capital=’人民币100万元’

1.请打印一下capital的长度

capital='人民币100万元'
print(len(capital))

7. 字符串函数

请用python语言判断capital是否是数字

capital='人民币100万元'
print(capital.isdigit())

8. 列表基本操作

定义列表:list1 = [‘life’,’is’,’short’],

       list2 = ['you','need','python']

完成以下几个要求:

1)输出python及其下标
2)在list2后追加 ‘!’ , 在 ‘short’ 后添加 ‘,’
3)将两个字符串合并后,排序并输出其长度
4)将 ‘python’ 改为 ‘python3’
5)移除之前添加的 ‘!’ 和 ‘,’

# 1
list1 = ['life','is','short']
list2 = ['you','need','python']
print(list2.index('python'))

# 2
list1 = ['life','is','short']
list2 = ['you','need','python']
n=list1.index('short')
list1.insert(n+1,',')
print(list1)

# 3
list1 = ['life','is','short']
list2 = ['you','need','python']
list1.extend(list2)
print(len(list1))
print(list1,list1.sort())

# 4
list1 = ['life','is','short']
list2 = ['you','need','python']
list2[list2.index('python')]='python3'
print(list2)

# 5 
list1 = ['life','is','short',',']
list2 = ['you','need','python','!']
list1.remove(',')
list2.remove(list2[list2.index('!')])
print(list1,list2)


9. 自己定义元组并练习常用方法(输出元组长度、指定位置元素等)

tup1 = (1,2,3,4,5,6,7)
tup2 = ('you', 'need', 'python')
print(tup1[0])
print(len(tup2))

10. 列表转换

定义列表:

list1 = [‘life’,’is’,’short’],

list2 = [‘you’,’need’,’python’]

list3 = [1,2,3,4,5,3,4,2,1,5,7,9]

完成以下操作:

1)构造集合 list_set1
2)将list1和list2合并构造集合 list_set2
3)输出两个集合的长度
4)将两个集合合并后移除 ‘python’
5)在合并后的新列表中添加 ‘python3’

# 1
list1 = ['life', 'is', 'short']
list2 = ['you', 'need', 'python']
list3 = [1, 2, 3, 4, 5, 3, 4, 2, 1, 5, 7, 9]
list_set1=set(list1+list2+list3)
print(list_set1)

# 2
list1 = ['life', 'is', 'short']
list2 = ['you', 'need', 'python']
list3 = [1, 2, 3, 4, 5, 3, 4, 2, 1, 5, 7, 9]
list_set2=set(list1+list2)
print(list_set2)

# 3 
list_set1=set(list1+list2+list3) list_set2=set(list1+list2) print(len(list_set1),len(list_set2))

# 4
list_set1.update(list_set2)
list_set1.remove('python')
print(list_set1)

# 5 
list_set1.add('python3')
print(list_set1)

发表回复

登录... 后才能评论