python中字符串的常用操作

# 例子
poem = ''' All that doth flow we cannot liquid name
Or else would fire and water be the same;
But that is liquid which is moist and wet
Fire that property can never get.
Then 'tis not could that doth the fire put out
But 'tis the wet that makes it die, no doubt.'''

# 判断文章是不是以All开头
poem.startwith('All')
# True

# 判断文章是不是以Or else would fire and water be the same结尾
poem.endwith('Or else would fire and water be the same')
# False

# 诗中第一次出现'the'的位置
word = 'the'
poem.find('the')
# 73

# 诗中最后一次出现'the'的位移量
poem.rfind(word)
# 214

# the在诗中出现了多少次
poem.count(word)
# 3

# 诗中所有字符都是字母和数字么?
poem.isalnum()
# False

字符串大小写变换

str = 'a duck goes into a barmmmm'

# 将结尾的m都删去
str.strip('m')
# a duck goes into a bar

# 将字符串首字母变成大写
str.capitalize()
# A duck goes into a bar...

# 将所有单词的开头字母都变成大写
str.title()
# A Duck Goes Into A Bar...

# 将所有字母都变成大写
str.upper()
# A DUCK DOES INTO A BAR...

# 将所有字母都转换为小写
str.lower()
# a duck goes into a bar...

# 将所有字母的大小写转换
str.swapcase()
# A DUCK DOES INTO A BAR...

# 将字符居中,此处假设字符串被排版在指定长度(30个字符)的空间里
str.center(30)
# '   a duck goes into a bar...   '

# 字符串左对齐
str.ljust(30)
# 'a duck goes into a bar...   '

# 将所有字符右对齐
str.rjust(30)
# '    a duck goes into a bar...'

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值