python--字符串格式化和列表
python--字符串格式化和列表
作业
3、用python实现"hello world hello python" 变成 python hello world hello
str_1 = "hello world hello python"
# 使用字符串的 split() 方法将字符串分割成单词列表(空格)
new_str = str_1.split()
#print(new_str)
# 使用字符串的 join() 方法将反转后的单词列表连接成一个字符串
res = " ".join(new_str[::-1])
# 打印结果
print(res)
字符串格式化
1、%s
2、%d int(正数、负数) 、float(会抹掉小数部分)
3、%f price = “the price is %.2f” %(9.9)
# %d
price = "the price is %d" %(9.9)
print(price)
# %f(保留2位置)
price = "the price is %.2f" %(9.9)
print(price)
format()
按顺序取值
price = “the price is {} {} {}”.format(10.99,100,200)
# 按顺序取值
price = "the price is {} {} {}".format(10.99,100,200)
print(price)
按索引取值(0开始)
price =“the price is {0} {1} {1}”.format(100,200)
# 按索引取值(0开始)
price ="the price is {0} {1} {1}".format(100,200,100)
print(price)
按关键字取值
price =“the price is {price1} {price1} {price2}”.format(price2=200,price1=100)
#按关键字取值
price ="the price is {price1} {price1} {price2}".format(price2=200,price1=100)
print(price)
调整精度
price =“the price is {:.2f}”.format(12.5364675)
#调整精度
# price = "the price is %.2f" %(9.9)
price ="the price is {:.2f}".format(12.5364675)
print(price)
百分比格式化
price =“the price is {:.2%}”.format(0.5364675)
# 百分比格式化
price ="the price is {:.2%}".format(0.5364675)
print(price)
列表
列表的特点
1、索引从0开始
2、list是有序的
3、可变的
4、元素可以重复
5、同一个listr支持任意数据类型
列表的创建
list_1=[1,2,3,4,5]
列表的增
list_1=[1,2,3,4,5]
列表的删
3.1 list.pop(index)
index=None:删除最后一个元素
index=索引值:删除对应索引的元素
正确删除了返回被删除的元素
# pop
list_1=[1,2,3,4,5,'adfadf','bdfd']
result=list_1.pop(0)
print(result)
3.2 list_1.remove(2)
删除匹配到的第一个元素
如果说元素匹配失败,直接报错
正确删除返回None
# remove 移除/删除
list_1=[1,2,3,4,5]
result=list_1.remove(2)
print(result)
3.3 clear() 清空列表
# 删除
list_1=[1,2,3,4,5,6]
# clear
result=list_1.clear()
print(list_1)
print(result)
3.4 del list_1[index]
按索引删除,没返回值
列表的改
4.1修改元素的值
list_1[index]=value
4.2插队元素insert
list_1=[1,2,3,4,5,'adfadf','bdfd']
list_1.insert(1,'test_insert')
print(list_1)
4.3合并元素extend
list_1=[1,2,3,4,5,'adfadf','bdfd']
list_2=['a','b','c']
list_1.extend(list_2)
print('这里是list_1:',list_1)
print('这里是list_2',list_2)
列表的查
5.1 通过索引获取元素
list_1[index]
5.2 获取元素的索引
list_1.index(value)
5.3 获取列表长度
len(list_1)
5.4 切片
list[开始索引:结束索引:步长]