字符串支持的函数:
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")返回结果: 布尔值

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

被折叠的 条评论
为什么被折叠?



