python--字符串格式化和列表

本文详细介绍了Python中字符串的格式化方法,包括`format()`函数的按顺序、索引和关键字取值,以及不同类型的格式化如整数、浮点数和百分比。此外,还涵盖了列表的基本操作,如创建、增删改查,以及列表的特点和常用方法如切片和索引查找。
摘要由CSDN通过智能技术生成

作业

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[开始索引:结束索引:步长]
  • 18
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值