二十六.python中字符串支持的函数

本文介绍了Python中字符串的基础操作方法,包括转换大小写、查找子串、分割字符串及判断字符串的开头和结尾等实用函数。通过具体实例展示了upper(), lower(), capitalize(), find(), split(), startswith() 和 endswith() 的使用方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串支持的函数:

1. upper(),lower(),capitalize()

例:

#coding:utf-8
s = "helLoPyThoN"

# 返回一个新的字符串
print s.upper()   #全部字母大写格式
print s.lower()   # 全部字母小写格式
print s.capitalize() # 首字母大写格式
# 原字符串是没有被修改的
print s

返回结果:



2. find()

例:

s = "Ilovepython!"
# find() 查找子字符串,返回子串的首字符索引
print s.find("love")
print s.find("py")
# 当不包含子串时,返回-1
print s.find("hcon")

返回结果:

love 其中l在字符串中索引值为1     py 索引值为5           hcon不包含该子串时返回-1


3. split()

s = "Hello World"
# s = "Hello:Wor:ld"
# 字符串分割,以列表形式返回分割后的部分
# 指定以:作为分割字符
# print s.split(':')
# 默认以空格作为分割字符
print s.split()

返回结果:以列表形式返回。



4. startswith(),endswith()

例:

# 判断字符串以xxx开头/结尾
print "helloworld".startswith("a")
print "helloworld".startswith("hel")
print "helloworld".endswith("ld")

返回结果:  布尔值


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值