字符串
1. 字符串的定义和遍历
字符串是 Python 中最常用的数据类型。我们可以使用引号 ’ 或 " 来创建字符串。
str1 = "hello python"
str2 = '你好啊!"python"'
print(str2)
print(str1[6])
for char in str2:
print(char)
2. 字符串的统计
hello_str = "hello hello"
print(len(hello_str))
print(hello_str.count("llo"))
print(hello_str.count("abc"))
print(hello_str.count("llo",6,11))
print(hello_str.index("llo"))
print(hello_str.index("llo",6,11))
3. 字符串的判断方法
space_str = " "
str1 = "hahahah "
print(space_str.isspace())
print(str1.isspace())
str1 = "runoob2016"
str2 = "23443434"
str3 = "1.1"
str4 = "\u00b2"
str5 = "一千零一"
print(str1.isdecimal())
print(str2.isdecimal())
print(str3.isdecimal())
print(str4.isdecimal())
print(str4.isdecimal())
print(str1.isdigit())
print(str2.isdigit())
print(str3.isdigit())
print(str4.isdigit())
print(str5.isdigit())
print(str1.isnumeric())
print(str2.isnumeric())
print(str3.isnumeric())
print(str4.isnumeric())
print(str5.isnumeric())
4. 字符串的查找和替换
hello_str = "hello world"
print(hello_str.startswith("hello"))
print(hello_str.startswith("o",7,11))
print(hello_str.endswith("world"))
print(hello_str.endswith("w",4,7))
print(hello_str.find("llo"))
print(hello_str.find("llo",1,4))
print(hello_str.find("abc"))
print(hello_str.replace("world", "python"))
print(hello_str)
5. 字符串文本对齐
poem = ["\t\n登鹳雀楼",
"王之涣",
"白日依山尽\t\n",
"黄河入海流",
"欲穷千里目",
"更上一层楼"]
print(poem)
for poem_str in poem:
print("|%s|" % poem_str.strip().center(10, " "))
6. 字符串的拆分和拼接
poem_str = "登鹳雀楼\t 王之涣 \t 白日依山尽 \t \n 黄河入海流 \t\t 欲穷千里目 \t\t\n更上一层楼"
print(poem_str)
poem_list = poem_str.split()
print(poem_list)
result = ",".join(poem_list)
print(result)
7. 转义字符
print('\\')
print('\'')
print("\'")
print("'")
print("\"")
print('\"')
print('"')
print("123\n456")
print('这是一串添加单引号的\'字符串\'')
print("这边是另一串添加了双引号的\"字符串\"")
|