str1 = "hello python" str2 = '我的外号是"大西瓜"' print(str1[1]) print(str2) for char in str2: print(char) hello_str = "hello hello" # 统计字符串的长度 print(len(hello_str)) # 统计某一个小(子)字符串出先的次数 print(hello_str.count("llo")) print(hello_str.count("abc")) # 某一个 子字符串出现的位置 print(hello_str.index("llo")) # 注意:如果使用index 方法传递的子字符串不存在,程序会报错! print(hello_str.index("abc"))
# 1. 判断空白字符 space_str = " \t\n\r" print(space_str.isspace()) # 2. 判断字符串中是否只包含数字 # 1> 都不能判断小数 # num_str = "1.1 # 2> unicode 字符串 # num_str = "\u00b2" # 3> 中文数字 num_str = "一千零一" print(num_str) print(num_str.isdecimal()) print(num_str.isdigit()) print(num_str.isnumeric()) hello_str = "hello word" # 1. 判断是否以指定的字符串开始 print(hello_str.startswith("Hello")) # 2. 判断是否指定的字符串结束 print(hello_str.endswith("word")) # 3.查找指定的字符串 # index 同样可以查找到指定的字符串在大字符串中的索引 print(hello_str.find("llo")) print(hello_str.find("abc")) # index 如果指定的字符串不存在会报错 # find 如果指定的字符串不存在,会返回-1 # 4.替换字符串 # replace 方法会返回一个新的字符串 # 注意: 不会修改原有字符串的内容 print(hello_str.replace("word", "python")) print(hello_str)
# 假设: 以下内容是从网络上抓取的 # 要求: 顺序并且居中对齐输出以下内容 poem = ["登黄鹤楼", "王之涣", "黄河依山尽", "欲穷千里目", "更上一层楼"] for poem_str in poem: print("|%s|" % poem_str.center(10,"#")) # 假设: 以下内容是从网络上抓取的 # 要求: 顺序并且居中对齐输出以下内容 poem = ["\t\n登黄鹤楼", "王之涣", "黄河依山尽\t\n", "欲穷千里目", "更上一层楼"] for poem_str in poem: # 先使用stirp 方法去除字符串中的空白字符 # 在使用center方法居中显示文本 print("|%s|" % poem_str.strip().center(10,"#")) # 假设: 以下内容是从网络上抓取的 # 要求: 将字符串中的空白字符全部去掉 # 在使用 "" 作为分隔符,拼接成一个完整的字符串 poem_str= "登黄鹤楼\t王之涣\t黄河依山尽\t欲穷千里目\t更上一层楼" print(poem_str) # 1 拆分字符串 poem_list =poem_str.split() print(poem_list) # 2 合并字符串 result = " ".join(poem_list) print(result)