Python 字符串 String 内建函数大全(1)

这篇博客详细介绍了Python字符串处理的多个内建函数,包括capitalize()、center()、count()、decode()、encode()等,涵盖了字符串的格式调整、查找、编码解码等功能,适合Python初学者参考。
摘要由CSDN通过智能技术生成

关于 Python 的字符串处理相关的方法还是非常多的,由于我正在学习 Python,于是就把 Python 中这些混杂的用于 string 的函数总结出来,在自己忘记的时候便于查找,希望对于有类似需求的人有所帮助。

captalize() 函数

功能

将一个字符串的第一个字母大写

用法

str.captalize()

参数

返回值

string

示例代码

str = "hello world!"

print "str.capitalize(): ", str.capitalize()

运行结果

tr.capitalize():  Hello world!

center(width, fillchar) 函数

将字符串居中,居中后的长度为 width

功能

将字符串居中,居中后的长度为 width

用法

str.center(width[, fillchar])

参数

  • width: 表示字符串总长度
  • fillchar: 使字符串居中所填充的字符,默认为空格

返回值

返回填充字符后的字符串

示例代码

str = "hello world!"

print "str.center(20): ", str.center(20)
print "str.center(20,'-'): ", str.center(20,'-')

运行结果

tr.center(20):      hello world!
str.center(20,'-'):  ----hello world!----

count(str, start=0, end=len(string)) 函数

功能

返回该字符串中出现某字符串序列(或字符)的次数

用法

str.count(sub, start=0, end=len(string))

参数

  • sub: 被查找的字符串序列
  • start: 开始查找的索引位置,默认为字符串开始
  • end: 结束查找的索引位置,默认为字符串结束

返回值

被查找的序列在字符串的查找位置中出现的次数

示例代码

str = "hello world! hello world!"

sub = "o"
print "str.count(sub): ", str.count(sub)

sub = "hello"
print "str.count(sub, 5) ", str.count(sub, 5)

运行结果

str.count(sub):  4
str.count(sub, 5)  1

decode(encoding=’UTF-8’,errors=’strict’) 函数 & encode(encoding=’UTF-8’,errors=’strict’)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值