Python字符串操作

创建字符串

创建字符串的四种方式:单引号、双引号、三引号、str方法

s_str='Python'
d_str="Python"
t_str='''Python'''
tt_str="""Python"""

my_number=123
my_string=str(my_number)

字符串连接

使用 +

str_one="Hello"
str_two="Python"
str_three=str_one+str_two

字符串方法

字符串是一个对象,对象有自己的属性和方法,使用 dir() 可以查看字符串所有的方法,使用 help() 可以查看某个方法的使用介绍

my_str="This is a string!"
dir(my_str)
help(my_str.upper)

字符串切片

字符串的下标从0 开始

字符串切片可表示为:[start:end:step] ,start默认为0,end默认为字符串的长度,step默认为1

字符串切片包含头(start),不包含尾(end)

字符串的最后一个字符的下标除了用 字符串的长度-1 表示外,还可以用 -1 表示

my_str="I like Python"
my_str[:1] 	# 'I'
my_str[:-5] 	#'I like Py'
my_str[:] 	#"I like Python"

字符串格式化

%s 代表字符串,%i 代表整数,%f 代表浮点数,默认保留 6 位小数,浮点数可以可以决定保留几位小数,例如 %.2f 代表保留2位小数

# 使用旧的方法
my_str="I like %s" % "Python" 	# I like Python
another_str="I like %s and %s" % ("Python","Java") 	# I like Python and Java

i_str="%i+%i=%i" %(1,2,3)	# 1+2=3

f_str="%f" %(1.23)	# 1.230000
ff_str="%.2f" %(1.23)	# 1.23

# 使用模板(template)
t_str="%(lang)s is fun!" %{"lang":"Python"}	# Python is fun!
print("%(value)s %(value)s %(value)s !" %{"value":"SPAM"})	# SPAM SPAM SPAM !

# 使用位置参数
"Python is as simple as {0},{1},{2}".format("a","b","c")	# Python is as simple as a,b,c
"Python is as simple as {1},{0},{2}".format("a","b","c")	# Python is as simple as b,a,c
xy={"x":0,"y":10}
print("Graph a point at where x={x} and y={y}".format(**xy))	# Graph a point at where x=0 and y=10
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

X+Y=Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值