字符串操作之字符串常用方法

 

常用的几个方法

① capitalize()

把字符串的首字母大写

例:

a="hello"

print(a.capitalize())

输出结果:”Hello“

② center(width)

用法:str.center(width,指定字符)

将原字符串用空格填充成一个长度为width的字符串,原字符串内容居中。

例:

a= 'hello'

print(a.center(10))

输出结果: hello #两边有空格,内容居中

例:

a= 'hello'

print(a.center(11,"$"))

输出结果:”$$$hello$$$“

③ count()

用法:str.count(sub, start,end))

返回字符串s在str中出现的次数

例:

a= "hello"

print(a.count('l'))

输出结果”:”2“

例:

a= "hello"

print(a.count('l',3))

输出结果:”1“

④strip()

返回截掉字符串的空格或指定字符后生成的新字符串,lstrip去除左侧指定字符,rstrip去除右侧指定字符。

例:

a= " hello "

print(a.strip())

输出为:

“hello”

例:

a=" hello "

print(a.lstrip())

输出为:“hello ”

例:

a= " hello "

print(a.rstrip())

输出为:“ hello”

⑤endswith()/startswitch()

判断字符串str是否以字符串s结尾/开始

例:

a='hello'

print(a.startswith('h'))

print(a.endswith('b'))

输出结果:True

False

⑥find()与index()

用法:string.find(str, beg=0, end=len(string))

检测 str 是否包含在 string 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1。

index的用法与find相同,区别在于如果未找到会报错。

例:

a="hello python"

print(a.find('l'))

输出结果:“2”

例:

a="hello python"

print(a.find('b'))

输出结果:“-1”

例;a="hello python"

print(a.index('b'))

报错

⑦lower()与upper()

lower():将字符串中所有大写字符为小写

upper():将字符串中所有小写字符为大写

例:

a="Hello"

print(a.lower())

print(a.upper())

输出结果:hello

HELLO

举报/反馈

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值