字符串
字符串定义
定义字符串hello_str = " "
查看列表功能hello_str+Tab
字符串常用操作
hello_str = "hello hello"
#1、统计字符串长度
print(len(hello_str))
#2、统计某一个字符串出现的次数
print(hello_str.count("llo"))
#3、某一个子字符串出现的位置
print(hello_str.index("llo"))
#1、判断空白字符
space_str = " \t\n\r"#都属于空白字符
print(space_str.isspace())
#2、判断字符串中是否包含数字
num_str = "(1)"#unicode字符串
print(num_str)
print(num_str.isdecimal())
print(num_str.isdigit())
print(num_str.isnumeric())
hello_str = "hello world"
#1、判断是否以指定字符串开始
print(hello_str.startswith("hello"))
#2、判断是否可以指定字符串结束
print(hello_str.endswith("world"))
#3、查找指定字符
#index同样可以查找指定的字符串在大字符串中的索引
print(hello_str.find("llo"))
#index如果指定的字符串不存在会报错
#find如果指定的字符串不存在会返回-1
print(hello_str.find("abc"))
#4、替换字符串
#replace方法执行完成后,会返回一个新的字符串,且不会修改原有字符串内容
print(hello_str.replace("world" , "python"))
print(hello_str)
#假设:以上内容是从网络上抓取的
#要求:顺序并且居中对齐输出一下内容
poem = ["登鹳雀楼",
"王之涣",
"白日依山尽\t\n",
"黄河入海流",
"欲穷千里目",
"更上一层楼"]
for poem_str in poem:
#先使用strip方法去除字符串中的空白字符
#再使用center方法居中显示文本
print("|%s|" % poem_str.strip().center(11 , " "))
#假设:以上内容是从网上抓取的
#要求:
#1、将字符串中的空白字符全部去掉
#2、再使用“ ”作为分隔符,拼接成一个整齐的字符串
poem_str = "登鹳雀楼 \t 王之涣 \t 白日依山尽 \t\n 黄河入海流 \t\t 欲穷千里目 \t 更上一层楼"
print(poem_str)
#1、拆分字符串
poem_list = poem_str.split()
print(poem_list)
#2、合并字符串
result = " ".join(poem_list)
print(result)
字符串切片
字符串[开始索引:结束索引:步长]
不同容器的公共方法
Python内置函数
切片
运算符
完整的for循环算法
for num in [1, 2, 3]:
print(num)
if num == 2:
break
else:
print("会执行吗?")
print("循环结束")
students = [
{"name": "阿土"},
{"name": "小美"}
]
#在学员列表中搜索指定的姓名
find_name = "李四"
for stu_dict in students:
print(stu_dict)
if stu_dict["name"] == find_name:
print("找到了 %s" % find_name)
#如果已经找到,应该直接退出循环,而不再遍历后续的元素
break
else:
#如果希望搜索列表时,所有的字典检查之时,都没有发现需要搜索的目标
#还希望得到一个统一的提示!
print("抱歉没有找到 %s" % find_name)
print("循环结束")