Python的几个字符串方法

本文介绍了Python中七个常用的字符串处理函数:capitalize()用于首字母大写,casefold()转换为全小写,center()实现字符串居中并填充,count()统计子串出现次数,encode()进行字符编码,endswith()检查字符串是否以指定后缀结尾,以及find()查找子串首次出现的位置。这些函数在文本处理中十分实用。
摘要由CSDN通过智能技术生成

1. capitalize()

将字符串变为首字母大写的格式。
示例:

str = 'my name is jack.'
print(str.capitalize())

输出:

My name is jack.

2. casefold()

将字符串全部转化为小写格式。
示例:

text = 'Success Can Be Difficult To Measure'
x = text.casefold()
print(x)

输出:

success can be difficult to measure

3. center()

将字符串置中,并在开头和结尾填充特定的字符。
用法:

str.center(width, fillChar)
  • witdth - 转化后的总长度
  • fillChar - 填充的字符,默认是’ ’

示例:

text = '今日多云转晴'
x = text.center(14)
print(x)
x2 = text.center(14, '|')
print(x2)

输出:

    今日多云转晴    
||||今日多云转晴||||

4. count()

返回字符串中某个子串出现的次数。
用法:

str.count(substring, start, end)
  • subsring - 需要统计的子串
  • start - 开始查找的下标值,默认为0
  • end - 结束查找的下标值,默认查找到最后一个字符
    示例:
text = 'python is an amazing laguage, I love python'
res = text.count('python')
print(res)

输出:

2

5. encode()

将字符编码为需要的格式。
用法:

string.encode(encoding='UTF-8',errors='strict')
  • encoding - 编码类型,默认’UTF-8’
  • errors
    • ‘strict’ - (默认) 失败时引发异常
    • ‘ignore’ - 忽略不可编码的字符
    • ‘replace’ - 遇到不可编码字符时,将其替换为’?’
    • ‘xmlcharrefreplace’ - 用 xml 字符替换字符
    • ‘namereplace’ - 用解释字符的文本替换字符
    • backslashreplace’ - 使用反斜杠代替无法编码的字符
      示例:
s = "Hello Python"
s1 = s.encode("ascii", "replace")
print(s1)

输出:

b’Hello Python’

6. endswith()

判断字符串是否由某个子串结尾。
用法:

str.endsWith(suffix, start, end)
  • suffix - 需要判断的后缀
  • start - 判断的起始位置
  • end - 判断的结尾位置
    示例:
files = ['car.jpg', 'plane.jpg', 'picture']
img = [file for file in files if file.endswith('.jpg')]
print(img)

输出:

[‘car.jpg’, ‘plane.jpg’]

7. find()

返回某个子串首次出现的下标值,若不存在,返回-1
用法:

str.find(substr, start, end)

示例:

sentence = 'Good Morning, Hello! Hello? How are you?'
# 1 first occurrence of 'Hello' (Case Sensitive)
result = sentence.find('Hello')
print("#1:",result)
# 2 returns -1 if substring not found
result = sentence.find('Bye')
print("#2:", result)

输出:

#1: 14
#2: -1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值