最近在图像识别过程中遇到基础代码读不懂的问题,发现自己Python基础真差,于是就来刷一刷基础题目。虽然练习的操作内容和图像识别无关,但其中碰到的一些小问题以及报错内容在日常代码中会遇到,下次就可以直接自己改,而不用再傻傻寻找帮助了,我认为练习一下也是有帮助的,原题来自吐血整理 python最全习题100道(含答案)持续更新题目,建议收藏!,我自己练了2遍,对一些地方加了修改,欢迎大家提出修改。
字符串问题
- 已知一个字符串为 “hello_world_yoyo”,如何得到一个队列[“hello”,“world”,“yoyo”]
使用split()函数将字符串转化为列表
str1="hello_world_yoyo"
strlist=str1.split("_")
print(strlist)
- 有个列表[‘hello’, ‘world’,
‘yoyo’]如何把把列表里面的字符串联起来,得到字符串"hello_world_yoyo"
使用join函数将列表转化为字符串:string_name.join(iterable)
strlist=['hello', 'world', 'yoyo']
str="_".join(strlist)
print(str)
3.输入: “We are happy”
输出:“We%20are%20happy.”
replace()函数实现字符串的替换
str1="We are happy"
print(str1.replace(" ","%"))
4.找出单词"welcome"在 字符串"Hello,welcome to my world" 中出现的位置,找不到返回-1
find()函数只会输出第一个被找到的索引位置,从0开始
str="Hello,welcome to my world"
print(str.find("welcome"))
5.#统计字符串"Hello,welcome to my world" 中字母w出现的次数和单词 my 出现的次数
count()函数
str="Hello,welcome to my world"
print(str.count("w"),str.count("my"))
6.输入一个字符串str, 输出第m个只出现过n次的字符,如在字符串" gbgkkdehh "中,找出第2个只出现1 次的字符,输出结果:d
str1=" gbgkkdehh "
zifu=[]
def findtext(m,n):
for i in str1:
if str1.count(i)==n:
zifu.append(i)
return zifu[m-1]
print(findtext(2,1))
7.判断字符串a=="Hello,welcome to my world"是否包含单词b=“world”,包含返回True,不包含返回 False
str1="Hello,welcome to my world"
b="world"
res=str1.find(b)
if res==-1:
print('False')
else:
print('True')
8.输出指定字符串A在字符串B中最后出现的位置,从 0 开始计数,没出现就输出-1
rfind函数的用法:rfind()函数用于返回字符串最后一次出现的位置(从右向左查询)
A="hello"
B="hi how are you hello world, hello yoyo !"
print(B.rfind(A)
9.#将字符串a="This is string example….wow!"全部转成大写或者小写
upper()和lower()函数转换成大小写
a="This is string example….wow!"
print(a.upper())
print(a.lower())
10.#将字符串 a =" Hello,welcome to my world "首尾空格去掉
strip()去掉首位空格,lstrip()去掉首空格,rstrip()去掉尾空格
a =" Hello,welcome to my world "
a.strip()
11.s=“ajldjlajfdljfddd”,去重并从小到大排序输出”adfjl”
set() 函数创建无序不重复元素集,可用于去除
s="ajldjlajfdljfddd"
sset=sorted(set(s))
#sorted默认升序,降序加入reverse = True
str1sset="".join(sset)
print(str1sset)
列表问题
1.如果有一个列表a=[1,3,5,7,11],反转成[11,7,5,3,1],取到奇数位值的数字,如[1,5,11]
[::-1]倒序输出
a=[1,3,5,7,11]
b=a[::-1]
jishu=[a[i] for i in range(0,len(a),2)]
print(b,jishu)
2.对列表a 中的数字从小到大排序
a = [1, 6, 8, 11, 9, 1, 8, 6, 8, 7, 8]
print(sorted(a))
3.找出列表中最大值和最小值
max()和min()
L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
print(max(L1),min(L1))
4.找出列表中单词最长的一个
a=["hello","world","yoyo","congratulations"]
lo=""
for i in a:
if len(i)>len(lo):
lo=i
print(lo)
5.取出列表中最大的三个值
L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
print(sorted(L1,reverse=True)[:3])
6.a = [1, -6, 2, -5, 9, 4, 20, -3] ,按列表中的数字绝对值从小到大排序
abslist=[]
for i in range