字符串

Python 的数据类型

Jason Myers

Instructor

创建格式化字符串

  • f 字符串(格式化字面量)- f""
cookie_name = "Anzac"
cookie_price = "$1.99"

print(f"Each { cookie_name } cookie costs { cookie_price }.")
"Each Anzac cookie costs $1.99."
Python 的数据类型

用字符串连接

  • "".join() 用调用它的字符串连接一个可迭代对象
child_ages = ["3", "4", "7", "8"]

print(", ".join(child_ages))
"3, 4, 7, 8"
print(f"The children are ages {','.join(child_ages[0:3])}, and {child_ages[-1]}.")
"The children are ages 3, 4, 7, and 8."
Python 的数据类型

匹配字符串的部分

  • .startswith().endswith() 判断字符串是否以某字符或子串开头/结尾
boy_names = ["Mohamed", "Youssef", "Ahmed"]
print([name for name in boy_names if name.startswith('A')])
["Ahmed"]
  • 注意:这些方法及大多数字符串函数区分大小写。
Python 的数据类型

在字符串中搜索

  • in 运算符可在字符串等可迭代对象中查找值。
"long" in "Life is a long lesson in humility."
True
"life" in "Life is a long lesson in humility."
False
Python 的数据类型

实现不区分大小写的一种方法

  • .lower() 方法返回小写字符串
"life" in "Life is a long lesson in humility.".lower()
True
Python 的数据类型

Passons à la pratique !

Python 的数据类型

Preparing Video For Download...