Python 官方文档:入门教程 => 点击学习
目录1:访str单个字符2: 字符串连接3:str切片4:使用in 和not in 测试字符串5:str方法6:重复操作符7:分割字符串总结1:访str单个字符 #for循环迭代 n
#for循环迭代
name = 'Chengwei'
for ch in name:
print(ch, end=' ')
#C h e n g w e i
#索引
print(name[1])
#h
print(name[-1]) #最后一个为 -1
#i
#len()函数返回str字符串数量
print(len(name))
#8
message = 'hello' + 'world'
print(message)
#helloworld
message = 'helloworld'
print(message[2:4])
#ll
message = 'helloworld'
if 'hello' in message:
print('YES')
#YES
if 'aaa' not in message:
print('YES')
#YES
字符串测试方法
isalnum() | 如果str只包含字母或数字,并且长度至少为一个字符,则返回true。否则返回false |
isalpha() | 如果str只包含字母并且长度至少为一个字符,则返回true。否则返回false |
isdigit() | 如果str只包含数字如果str只包含字母并且长度至少为一个字符,则返回true。否则返回false |
islower() | 如果str中的所有字母都是小写如果str只包含数字如果str只包含字母并且长度至少为一个字符,则返回true。否则返回false |
isspace() | 如果str只包含空白字符,并且长度至少为一个字符,则返回true。否则返回false(空格,\n,\t) |
isupper() | 如果str中的所有字母都是大写如果str只包含数字如果str只包含字母并且长度至少为一个字符,则返回true。否则返回false |
字符串修改方法
lower() | 返回将所有字母转换为小写的str副本。不是字母的不变 |
lstrip() | 返回删除所有前导空白字符的str副本。 |
lstrip(str_item) | str_item是字符串。返回删除所有前导str_item的字符串副本 |
rstrip() | 返回所有尾部空白字符串的字符串副本。 |
rstrip(str_item) | 返回删除所有尾部str_item的字符串副本 |
strip() | |
strip(str_item) | 删除所有前导和尾部str_item的字符串副本 |
upper() |
lower() | 返回将所有字母转换为小写的str副本。不是字母的不变 |
lstrip() | 返回删除所有前导空白字符的str副本。 |
lstrip(str_item) | str_item是字符串。返回删除所有前导str_item的字符串副本 |
rstrip() | 返回所有尾部空白字符串的字符串副本。 |
rstrip(str_item) | 返回删除所有尾部str_item的字符串副本 |
strip() | |
strip(str_item) | 删除所有前导和尾部str_item的字符串副本 |
upper() |
搜索和替换的方法
endswith(substring) | 返回true或false |
find(substring) | 返回找到substring的最小索引位置。没有找到返回 -1 |
replace(old, new) | 返回将所有的old替换为new的字符串副本 |
starstwith(substring) | 返回true或false |
print('hello' * 2)
#hellohello
message = 'hello world chengwei'
message_list = message.split()
print(message_list)
#['hello', 'world', 'chengwei']
message = 'hello,world,chengwei'
message_list = message.split(',')
print(message_list)
#['hello', 'world', 'chengwei']
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程网的更多内容!
--结束END--
本文标题: 详解python字符串相关str
本文链接: https://www.lsjlt.com/news/162631.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0