作者:Yyao | 来源:互联网 | 2023-10-11 11:02
目录
- 1:访str单个字符
- 2: 字符串连接
- 3:str切片
- 4:使用in 和not in 测试字符串
- 5:str方法
- 6:重复操作符
- 7:分割字符串
- 总结
1:访str单个字符
#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
2: 字符串连接
message = "hello" + "world"
print(message)
#helloworld
3:str切片
message = "helloworld"
print(message[2:4])
#ll
4:使用in 和not in 测试字符串
message = "helloworld"
if "hello" in message:
print("YES")
#YES
if "aaa" not in message:
print("YES")
#YES
5:str方法
字符串测试方法
isalnum() | 如果str只包含字母或数字,并且长度至少为一个字符,则返回true。否则返回false |
isalpha() | 如果str只包含字母并且长度至少为一个字符,则返回true。否则返回false |
isdigit() | 如果str只包含数字如果str只包含字母并且长度至少为一个字符,则返回true。否则返回false |
islower() | 如果str中的所有字母都是小写如果str只包含数字如果str只包含字母并且长度至少为一个字符,则返回true。否则返回false |
isspace() | 如果str只包含空白字符,并且长度至少为一个字符,则返回true。否则返回false(空格,
, ) |
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 |
6:重复操作符
print("hello" * 2)
#hellohello
7:分割字符串
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"]
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程笔记的更多内容!