目录
startswith(判断字符串是否以xx开头? 得到一个布尔值)
endswith(判断字符串是否以xx结尾, 得到一个布尔值)
strip(去除字符串两边的空格、换行符、制表符、得到一个新字符串)
len()(获取字符串的长度)
这个为公共功能,字符串、列表、元组、字典都可以使用这个功能!
print(len('1')) #输出结果为1,字符串
print(len('你好')) #输出结果为2,字符串
print(len([1,2,3,4,5])) #输出结果为5,列表
print(len((1,2,3))) #输出结果为3,元组
print(len({'name':'小明','age':18})) #输出结果为2,字典
字符串的索引
以0开始 0-9个位数,用来获取字符串中某个字符的值:
(因为索引是从0开始,所以第n个字符的索引是n-1。当索引为负数时,表示倒数第n个字符,如-1时,表示最后一个字符)
name = "来一起学习python"
print('第一个字符为'+name[0])
print('第二个字符为'+name[1])
print('第七个字符为'+name[6])
print('倒数第一个字符为'+name[-1]) # -1 表示最后一个
print('倒数第二个字符为'+name[-2])
print('倒数第4个字符为'+name[-4])
切片
获取字符串中n个连续的字符的值 对序列型对象(list,str,tuple) 的一种高级索引方法,取出一个范围对应的元素。
语法格式:[start(开始):stop(停止):stride(步长)] 。取出来的字符串的结束字符是stop结束前的前一个字符。 stride表示步长, 间隔的取出字符串
str_content='python真好玩'
print(str_content[0:5:1]) #输出结果为:pytho,表示从第0位取到第5位,不包括第5位,步长为1
print(str_content[0:5:2]) #输出结果为:pto,表示从第0位取到第5位,不包括第5位,步长为2
print(str_content[2:6:2]) #输出结果为:to,表示从第2位取到第6位,不包括第6位,步长为2
其中每个参数都是可以省略的:
str_content='python真好玩'
print(str_content[0:5]) #输出结果为pytho,当省略布长时,布长默认为1
print(str_content[0::1]) #输出结果为pytho真好玩,当省略停止点时,停止点会默认最后一个
print(str_content[:5:1]) #输出结果为pytho,当起点省略时,起点默认为0
当步长为负数时:
表示从右往左逆序输出
str_content='python真好玩'
print(str_content[::-1]) #输出结果为玩好真nohtyp
列表与元组操作方法类似!
startswith(判断字符串是否以xx开头? 得到一个布尔值)
翻译为:以。。开始
content='hello world'
print(content.startswith('he')) #成立时为True
print(content.startswith('wo')) #不成立时False
endswith(判断字符串是否以xx结尾, 得到一个布尔值)
翻译为:以。。结束
content='hello world'
print(content.endswith('ld')) #成立时为True
print(content.endswith('he')) #不成立时False
isdecimal(判断字符串是否为十进制数)
翻译为:是十进制
height='174'
print(height.isdecimal()) #Ture
money='174.6'
print(money.isdecimal()) #False
name='小明'
print(name.isdecimal()) #False
strip(去除字符串两边的空格、换行符、制表符、得到一个新字符串)
翻译为:条
password=' hello world ' #字符串两边都有空格
print(password.strip()) #输出结果为hello world
upper (字符串全部变大写,得到一个新的字符串)
翻译为:上
content='hello world'
print(content.upper()) #输出结果为HELLO WORLD
lower(字符串全部变小写,得到一个新的字符串)
翻译为:降下
content='HELLO WORLD'
print(content.lower()) #输出结果为hello world
replace(字符串内容的全部替换)
翻译为:代替
content='python真不错!'
print(content.replace('不错','简单')) #输出结果为python真简单!
split(字符串的切割,得到一个新的列表)
翻译为:分裂
comtemt='我的名字叫小明!身高170!体重130。'
print(comtemt.split('!')) #输出结果为['我的名字叫小明', '身高170', '体重130。']
join(将列表中的元素拼接起来成为一个新的字符串)
翻译为:参加
list=['中国','美食真','好吃']
print('的'.join(list)) #输出结果为中国的美食真的好吃
title(将字符串的首字母变大写,其它不变)
翻译为:标题
name='hello,world'
print(name.title()) #输出结果为Hello,World
swapcase(将字符串的大写变小写,小写变大写)
翻译为:swap为交换,case为装 ... 入盒中
name='HELLO world'
print(name.swapcase()) #输出结果为hello WORLD
lstrip(删除字符串左边的空白字符串)
翻译为:l是left左边的缩写,strip翻译为条
content=' a'
print(content.lstrip()) #输出结果为a
rstrip(删除字符串右边的空白字符串)
翻译为:r是right右边的缩写,strip翻译为条
content='a '
print(content.rstrip()) #输出结果为a
后续为持续增加