1、判断操作
#isspace判断空白字符,制表符都属于空格\t\n\r
space_str=" \t\n\r"
print(space_str.isspace())
#判断字符串中是否只包含数字,不能判断小数
num_str="\u00b2"
print(num_str)
print(num_str.isdecimal())#功能比较少,只能判断普通的数字
print(num_str.isdigit())#数字、(1)?、\u00b2(上标2),这些都是Unicode字符串
print(num_str.isnumeric())#数字,中文数字
2、查找和替换
#查找替换
hello_str="hello world"
#1、判断是否以指定字符串开始
print(hello_str.startswith("hello"))
#2、判断是否以指定字符串结束
print(hello_str.endswith("world"))
#3、查找指定字符串
print(hello_str.find("llo"))
#find在指定字符串不存在,不会报错,并且输出-1,而index会报错
print(hello_str.find("abc"))
#4、替换字符串,replace执行完毕之后,会返回一个新的字符串,不会改变原有字符串
print(hello_str.replace("world","python"))
print(hello_str)
3、文本对齐
#文本对齐
poem=["登鹳雀楼",
"王之涣",
"白日依山尽",
"黄河入海流",
"欲穷千里目",
"更上一层楼"]
for poem_str in poem:
# print("|%s|"%poem_str.center(10," "))#空格要使用全角空格才能对齐,相当于使用中文模式
# print("|%s|" % poem_str.ljust(10, " "))#向左对齐
print("|%s|" % poem_str.rjust(10, " "))#文本向右对齐
4、去除空白符
#去除空白字符
poem=["\t\n登鹳雀楼",
"王之涣",
"白日依山尽\t\n",
"黄河入海流",
"欲穷千里目",
"更上一层楼"]
for poem_str in poem:
#先使用strip方法去除字符串中的空白字符
#在使用center方法居中显示文本
print("|%s|" % poem_str.strip().center(10, " "))
5、字符串拆分和连接
适用于从网上粘贴的文字中有空格什么的
poem_str="登鹳雀楼\t 王焕之 \t 白日依山尽 \t \n黄河入海流 \t\t欲穷千里目 更上一层楼"
print(poem_str)
poem_list=poem_str.split()#先拆分字符串,返回是一个列表
print(poem_list)
result=" ".join(poem_list)#返回的是一个字符串
print(result)
补充知识:字符串的切片
字符串[开始索引:结束索引:步长]
#字符串的切片
num_str="0123456789"
print(num_str[2:6])#截取2-5位置的数字
print(num_str[2:])#不指定末尾
print(num_str[0:6])#截取开始到6的位置,
print(num_str[:])#打印全部
print(num_str[::2])#每隔一个字符打印
print(num_str[1::2])#从索引1开始,每隔一个字符打印一下
print(num_str[-1])#取最后一个字符
print(num_str[2:-1])#从索引2开始,不包括最后一个字符
print(num_str[-2:])#取最后两个字符
print(num_str[-1::-1])#字符串逆序
print(num_str[::-1])#和上一句的功能是一样的