str1="hello python" str2='我的外号是"大西瓜"' print(str2) print(str1[6]) for char in str2: print(char) hello_str="hello hello" #1、统计字符串长度 print(len(hello_str)) #2、统计某一个小字符串出现的次数 print(hello_str.count("llo")) #3、某一个子字符串出现的位置 print(hello_str.index("llo")) #4、判断空白字符(包含\t\n\r) space_str=" " print(space_str.isspace()) #5、判断数字的三个方法 string.isdacimal() 如果string只包含数字返回True,全角数字 string.isdigit() 如果string只包含数字返回True,全角数字、(1)、\u00b2 string.isnumeric() 如果string只包含数字返回True,全角数字、汉字数字 #1都不能判断小数 # num_str="1.1" #2unicode 字符串 # num_str="\u00b2" #3中文数字 num_str="一千零一夜" print(num_str.isdecimal()) print(num_str.isdigit()) print(num_str.isnumeric())
#6、字符串的查找和替换
hello_str="hello world" #判断是否以指定字符开始 print(hello_str.startswith("hello")) #判断是否以指定字符结束 print(hello_str.endswith("world")) #查找指定字符串 #index同样可以查找指定的字符串在大字符串中的索引 #index 如果指定的字符串不存在,会报错 #find 如果指定的字符串不存在,会返回-1 print(hello_str.find("llo")) #替换字符串 print(hello_str.replace("world","python")) #replace 方法执行完成之后,会返回一个新的字符串,注意,不会修改原有字符串的内容
#7、文本对齐演练 #假设:以下内容是从网络上抓取的,要求顺序并且居中对齐输出以下内容 poem=["登鹳雀楼", "王之浣", "白日依山尽", "黄河入海流", "欲穷千里目", "更上一层楼"] for poem_str in poem: print(poem_str.center(9," "))
#8、去除空白字符
#假设:以下内容是从网络上抓取的,要求顺序并且居中对齐输出以下内容 poem=["\t\n登鹳雀楼", "王之浣", "白日依山尽\t\n", "黄河入海流", "欲穷千里目", "更上一层楼"] for poem_str in poem: #先使用strip方法去除字符串中的空白字符 #再使用center方法显示文本 print(poem_str.strip().center(10," "))
#9、拆分和拼接字符 #假设:以下内容是从网络上抓取的,要求将字符串中的空白字符全部去掉,再使用“ ”作为分隔符,拼接成一个整齐的字符串 poem_str="登鹳雀楼\t王之涣\t白日依山尽\t\n黄河入海流\t\t欲穷千里目\n\t更上一层楼" print(poem_str) #1、拆分字符串 poem_list=poem_str.split() print(poem_list) #2、合并字符串 result=" ".join(poem_list) print(result) #10、切片概念和语法以及倒序索引 #字符串[开始索引:结束索引:步长] num_str="0123456789" #截取2-5位置的字符串 print(num_str[2:6]) #截取2-末尾的字符串 print(num_str[2:]) #截取从开始到5的字符串 print(num_str[0:6]) #截取完整的字符串 print(num_str[:]) #从开始,每隔一个取一个 print(num_str[::2]) #从索引1开始,每隔一个取一个 print(num_str[1::2]) #截取2到末尾-1的字符串 print(num_str[2:-1]) #截取字符串末尾两个字符 print(num_str[-2:]) #字符串的逆序 print(num_str[-1::-1]) print(num_str[::-1])