quantity = 3
itemno = 567
price = 52
myorder = "I want {} pieces of item number {} for {:.2f} dollars."print(myorder.format(quantity, itemno, price))
使用索引号确保值对应正确占位符:
quantity = 3
itemno = 567
price = 52
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."print(myorder.format(quantity, itemno, price))
命名索引允许传递关键字参数:
myorder = "I have a {carname}, it is a {model}."print(myorder.format(carname="Porsche", model="911"))
常用方法
Python 提供了一组强大的内建字符串方法,它们通常返回新字符串而不修改原串。
方法
描述
capitalize()
把首字符转换为大写
casefold()
把字符串转换为小写(比 lower 更彻底)
center()
返回居中的字符串
count()
返回指定值在字符串中出现的次数
encode()
返回字符串的编码版本
endswith()
如果字符串以指定值结尾,则返回 true
expandtabs()
设置字符串的 tab 尺寸
find()
在字符串中搜索指定的值并返回它被找到的位置
format()
格式化字符串中的指定值
format_map()
格式化字符串中的指定值
index()
在字符串中搜索指定的值并返回它被找到的位置
isalnum()
如果字符串中的所有字符都是字母数字,则返回 True
isalpha()
如果字符串中的所有字符都在字母表中,则返回 True
isdigit()
如果字符串中的所有字符都是数字,则返回 True
islower()
如果字符串中的所有字符都是小写,则返回 True
join()
把可迭代对象的元素连接到字符串的末尾
lower()
把字符串转换为小写
lstrip()
返回字符串的左修剪版本
replace()
返回字符串,其中指定的值被替换为指定的值
split()
在指定的分隔符处拆分字符串,并返回列表
strip()
返回字符串的剪裁版本
upper()
把字符串转换为大写
zfill()
在字符串的开头填充指定数量的 0 值
面向对象编程
类定义
classPerson:
def__init__(self, name, age):
self.name = name
self.age = age
defmyfunc(self):
print(f"Hello my name is {self.name}")
p1 = Person("Bill", 63)
p1.myfunc()
属性与对象生命周期
判断对象是否为空:
if p1 isNone:
pass
删除属性或对象本身:
del p1.age
del p1
继承
classStudent(Person):
pass
运算符
算术运算符
运算符
名称
实例
+
加
x + y
-
减
x - y
*
乘
x * y
/
除
x / y
%
取模
x % y
**
幂
x ** y
//
地板除
x // y
赋值运算符
运算符
实例
等同于
=
x = 5
x = 5
+=
x += 3
x = x + 3
-=
x -= 3
x = x - 3
*=
x *= 3
x = x * 3
/=
x /= 3
x = x / 3
%=
x %= 3
x = x % 3
//=
x //= 3
x = x // 3
**=
x **= 3
x = x ** 3
&=
x &= 3
x = x & 3
^=
x ^= 3
x = x ^ 3
>>=
x >>= 3
x = x >> 3
<<=
x <<= 3
x = x << 3
比较、逻辑与身份运算符
比较运算符用于比较两个值(如 ==, !=, >, <)。逻辑运算符组合条件(and, or, not)。身份运算符比较内存地址(is, is not)。成员运算符测试序列存在性(in, not in)。
位运算符
用于二进制数字操作:
运算符
描述
&
AND
`
`
^
XOR
~
NOT
<<
Zero fill left shift
>>
Signed right shift
控制流
if-else
a = 200
b = 66if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
循环
while 循环
i = 1while i < 7:
print(i)
if i == 3:
break
i += 1
for 循环
遍历序列(列表、元组、字典、集合或字符串):
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
遍历字典:
d = {'name1': 'example', 'name2': '.', 'name3': 'com'}
for key, value in d.items():
print(key, 'value:', value)
range 函数
生成数字序列:
for x inrange(10):
print(x)
迭代器
迭代器是实现了 __iter__() 和 __next__() 方法的对象。
classMyNumbers:
def__iter__(self):
self.a = 1returnselfdef__next__(self):
ifself.a <= 20:
x = self.a
self.a += 1return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
函数
定义与 Lambda
defmy_function():
print("Hello from a function")
my_function()
# Lambda 匿名函数
x = lambda a, b, c: a + b + c
print(x(5, 6, 2))
异常处理
使用 try-except 捕获错误:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
else:
print("Nothing went wrong")
finally:
print("The 'try except' is finished")
模块与上下文管理器
模块导入
保存代码到 mymodule.py:
defgreeting(name):
print("Hello, " + name)
导入并使用:
import mymodule
mymodule.greeting("Bill")
with 语句
使用 with 可以自动管理资源(如文件关闭),即使发生异常也能安全释放。
withopen("1.txt") as file:
data = file.read()
底层原理涉及 __enter__() 和 __exit__() 方法。
日期与时间
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
y = datetime.datetime.now()
print(y)