定义
str = "hi"
str_1 = 'py'
str_2 = '我的"xxx"'
索引
string = "nihaoya"
for i in string:
print(i)
print(len(string))
print(string.count("a"))
print(string.count("abc"))
print(string.index("a"))
常用方法
菜鸟教程
转义字符
\ | 反斜杠符号 |
---|
’ | 单引号 |
" | 双引号 |
\n | 换行 |
\t | 横向制表符 |
\r | 回车 |
isspace()
space_str = " a"
print(space_str.isspace())
space_str = " "
print(space_str.isspace())
space_str = " \t\n\r"
print(space_str.isspace())
isnumeric()
查找和替换
hello_str ="hello a"
print(hello_str.startswith("Hello"))
print(hello_str.startswith("hello"))
print(hello_str.endswith("b"))
print(hello_str.index("llo"))
print(hello_str.find("aaa"))
print(hello_str.replace("a","b"))
poem =[ "登鹳雀楼",
"王之涣",
"白日依山尽",
"黄河入海流",
"欲穷千里目",
"更上一层楼"]
for i in poem:
print("|%s|"%i.center(10))
for i in poem:
print("|%s|" % i.ljust(10))
判断空白字符
space_str = " a"
print(space_str.isspace())
space_str = " "
print(space_str.isspace())
space_str = " \t\n\r"
print(space_str.isspace())
拆分、合并
poem = "\t\n登鹳雀楼 王之涣白日依山尽\t\n黄河入海流欲穷千里目更上一层楼"
print(poem)
poem_list =poem.split()
print(poem_list)
result = "".join(poem_list)
print(result)
切片
- 适用于:字符串、列表list、元组tuple
- 索引值:限定范围
- 列表和元组都是有序的集合
- 字典是一个无需的集合,是使用键值对保存数据
str[开始索引:结束索引:步进值]
str = "0123456789"
print(str[2:6])
print(str[2:5])
print(str[2:])
print(str[0:6])
print(str[:6])
print(str[:])
print(str[::2])
print(str[1::2])
print(str[-1])
print(str[2:-1])
print(str[-2:-1])
print(str[-2:])
print(str[0::-1])
print(str[-1::-1])