Python学习笔记(二)------基本类型------字符串

前言

本节针对字符串这个基本类型做个熟悉。

正文

字符串拼接

tang_str="hello python"
print(tang_str)
hello python
tang = "hello" + "python"
print(tang)
hellopython

字符串长度

len(tang_str)
12

字符串乘以固定值,会得到什么样的结果

tang_str * 3
'hello pythonhello pythonhello python'

字符串拆分

tang = '1 2 3 4 5'
tang.split()
['1', '2', '3', '4', '5']
tang = '1,2,3,4,5'
tang = tang.split(",")
print(tang)
['1', '2', '3', '4', '5']

字符串合并,按照固定分隔符

tang_str = ' '
tang_str.join(tang)
'1 2 3 4 5'

字符串替换

tang = 'hello python'
tang.replace("python", "world")
'hello world'
print(tang)
hello python

字符串大写输出

tang.upper()
'HELLO PYTHON'

字符串小写输出

tang.lower()
'hello python'

字符串去除左右空格

tang2 = "            hello python     "
tang2.strip()
'hello python'

字符串去除左空格

tang2.lstrip()
'hello python     '

字符串去除右空格

 tang2.rstrip()
'            hello python'

字符串格式化输出

'{} {} {}'.format('chen', 'mo', 'hello')
'chen mo hello'

按照顺序 2 0 1代表传入参数的输出顺序

'{2} {0} {1}'.format('chen', 'mo', 'hello')
'hello chen mo'
'{chen} {mo}'.format(chen='mo', mo='chen')
'mo chen'
chen = "chen mo"
a = 123.0
b = 456
result = '%s%f%d' % (chen,a,b)
print(result)
chen mo123.000000456

索引

前面是从0开始

chen = "chen mo"
chen[0]
'c'
chen[5]
'm'

后面是从-1开始

chen[-1]
'o'

:表示左闭右开区间

chen[0:4]
'chen'
chen[5:]
'mo'
chen[:4]
'chen'
chen[4:-2]
' '
chen[-2:]
'mo'
chen[::2]
'ce o'

字符串中是否包含mo

'mo' in chen
True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值