Python数据类型---字符串

表示

单引号、双引号、三引号
str = 'this is str'

通过下标取值

正向从0开始,反向从-1开始

字符串的切片

[start : end : step]---包前不包后
start开始位置下标
end结束位置下标
step步长

省略end,取到最后---str[1:]
省略start,从最开始位置取值---str[:4]
复制---str[:]
倒序---str[::-1] 	

字符串的常用方法

1.拼接
1)str.join()

test = '/'.join(["2020","08","03"])  #join(里面只能传一个参数)
print(test)   #结果:2020/08/03

2)通过“+”拼接

str_new = 'str'
new = 'new'
new_str = str_new + new
print(new_str)  #strnew

2.查找某字符或字符串的位置
1)find

name='abcecd'
name.find('b')   #1
name.find('c')  #2  存在多个时,得到第一个
name.find('bc') #2  返回第一个字符的位置
name.find('m')  #找不到时返回-1
name.find('ac') #不在一起时仍返回-1

2)index
与find区别在于,找不到元素时会报错
3.count–统计字符出现的次数

name.count('c')  #2

4.replace—替换

name.replace('a','m')  #'mbcecd'

5.split—切割

test="2020/08/03"
print(test.split('/'))  #分割所有---['2020', '08', '03']
print(test.split('/',1))  #分割第一个/---['2020', '08/03']

6.upper—所有字母都大写
lower—所有字母都小写

str = 'BJNGnis'
print(str.upper())    #BJNGNIS
print(str.lower())   #bjngnis

7.strip—去除字符串两边的特殊字符

str = ' BJNGnis '
print(str.strip())    #BJNGnis,不传时默认去除空格
str1 = '/CIcsji/'
print(str1.strip('/'))  #CIcsji

8.格式化
1)format

name = '苹果'
price = 5.56887
print('{}{}元/斤'.format(name,price))   #苹果5.56887元/斤
print('{}{:.2f}元/斤'.format(name,price))   #苹果5.57元/斤---{:.2f}保留小数点两位
print('{}{:.2%}元/斤'.format(name,price))  #苹果556.89%元/斤---{:.2%}百分比格式

2)f–string(3.6版本后支持)

print(f'{name}{price}元/斤')  #苹果5.56887元/斤

3)传统表示方法

print('my name is %s' % ('yatou')) #my name is yatou----%s格式化字符串
print('my age is %d' % (22))   #my age is 22----%d整型输出
print('price is %f' % (15.8))   #price is 15.800000----%f格式化浮点数
print('price is %.2f' % (15.8))  #price is 15.80----%.2f浮点数两位

9.len—字符串长度

name = '苹果'
print(len(name))  #2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值