常见的Python字符串操作

# str='乐视'
"""
d多行注释
字符串:一串字符连接在一起,Python中只要实在引号里面的,都是字符串
字符:
其他语言中:char声明的事字符,string生命的是字符串
"""

content='helloworld'
# 字符串切片操作,字符串也是一个容器,可以存放任意字符
# 容器里面的所有的元素都有一个编号
# 编号由0开始

print(content[3:6])
print(content[::-1])#反转字符串
print(content[1:4:2])#位置1,开始;位置2,结束;位置三,隔几位删除一个

----------find------------------------------------
content='hello word'
result=content.find('o')
print(result)#返回值-1表示没有找到,其他值表示位置
result=content.index('你好')#寻找字符在字符串中的位子
print(result)
-----------------count----------------------
content='hello world'
result=content.count('l')#指定字符在字符串中的个数
print(result)
-----------------replace-------------------
content='hello world'
result=content.replace('l','pq')
print(result)
------------------splite and 大小写转换-----------------------
content='Hello WORLD'
result=content.split('l')
print(result)
print(content.lower())#全部小写,支持英文
print(content.upper())#全部大写
print(content.capitalize())#首字母大写
print(content.casefold())#转化为小写,支持UTF-8

---------------------start ,end------------------------------------
content='Hello World'
print(content.startswith('w'))
print(content.endswith('d'))
-----------------maketrans--------------------
content='人生苦短,我用Python'
s=str.maketrans('苦短','sl')#规则
content=content.translate(s)#让content遵守规则
print(content)

猜你喜欢

转载自blog.csdn.net/qq_38059635/article/details/81192328