python字符串的操作

 

转载:https://www.cnblogs.com/hukey/p/9612961.html

字符串的操作方法:

1.   capitalize() :首字母大写

s1 = 'my heart will go on'
print(s1.capitalize())  # 首字母大写

# 执行结果:
# My heart will go on

2   upper() : 全部大写

s1 = 'my heart will go on'
print(s1.upper())   # 全部转为大写

# 执行结果:
# MY HEART WILL GO ON

3   lower() : 全部小写

4  title(): 标题首字母大写

5  center(): 居中,默认填充空格

6   count():统计字符串出现个数 

s1 = 'adfasdfasdfasdfertadf'
print(s1.count('a'))    # 统计字符串出现的次数

# 执行结果:
# 5

7  split(): 按照指定字符分隔成多个元素  str --> list

s1 = 'nice to meeting you'
print(s1.split())   # 默认将字符串通过空格分隔并组成列表类型

# 执行结果:
# ['nice', 'to', 'meeting', 'you']

9  replace(): 字符串替换

s1 = 'nice to meeting you'
print(s1.replace('meeting', 'see')) # 在字符串中,用第一个参数替换掉第二个参数,默认是匹配上则全部替换

# 执行结果:
# nice to see you

10 find() 和 index()

find() 和 index() 都是通过元素找索引的方法,区别如下:

find()方法:元素存在打印索引,元素不存在返回 -1

index()方法:元素存在打印索引,元素不存在报错。错误信息:ValueError: substring not found

复制代码

s1 = 'nice to meeting you'

print(s1.find('to'))

# 执行结果:
# 5

print(s1.find('xxx'))

# 执行结果:
# -1

print(s1.index('to'))

# 执行结果:
# 5

# print(s1.index('xxx'))

# 执行结果:
# ValueError: substring not found
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值