Python 变量、数字与字符串速查

本文整理 Python 最基础的数据类型:变量、数字、字符串的常用操作,适合快速查阅。

1. 变量基础

Python 是动态类型语言,变量不需要声明类型,直接赋值即可。

# 基本赋值
name = "Alice"
age = 25
height = 1.68
is_student = True

# 链式赋值
a = b = c = 0

# 多元赋值
x, y = 10, 20

变量命名规则

  • 只能包含字母、数字、下划线
  • 不能以数字开头
  • 区分大小写
  • 不能使用 Python 关键字
# 常用命名风格
user_name = "bob"        # 下划线命名 (snake_case)
UserName = "bob"        # 帕斯卡命名 (PascalCase)
USER_NAME = "bob"      # 常量大写

2. 数字类型

Python 支持三种数字类型:整数(int)、浮点数(float)、复数(complex)。

# 整数
a = 10          # 十进制
b = 0b1010      # 二进制 = 10
c = 0o12        # 八进制 = 10
d = 0xa         # 十六进制 = 10

# 浮点数
pi = 3.14159
scientific = 1.5e-3     # 0.0015

# 复数
complex_num = 3 + 4j
print(complex_num.real)  # 3.0
print(complex_num.imag)  # 4.0

数字运算

# 基本运算
5 + 3    # 8  加
5 - 3    # 2  减
5 * 3    # 15 乘
5 / 3    # 1.666... 除 (始终返回浮点数)
5 // 3   # 1  整除
5 % 3    # 2  取余
5 ** 3   # 125 幂

# 进阶运算
divmod(5, 3)    # (1, 2)  返回商和余数
abs(-5)          # 5  绝对值
round(3.14159, 2) # 3.14 四舍五入

类型转换

# 字符串转整数
int('123')           # 123
int('0xff', 16)      # 255 指定进制
int('1010', 2)      # 10 二进制字符串

# 字符串转浮点数
float('3.14')        # 3.14
float('1e-3')        # 0.001

# 整数转字符串
str(123)             # '123'
hex(255)             # '0xff'
bin(10)              # '0b1010'

# 转换为浮点数
float(10)            # 10.0

3. 字符串

Python 字符串用单引号、双引号、三引号均可。

# 创建字符串
s1 = 'hello'
s2 = "hello"
s3 = """多行
字符串"""

# 转义字符
path = "C:\\Users\\name"   # C:\Users\name
path_raw = r"C:\Users\name"  # 原始字符串

# 字符串拼接
"hello" + " " + "world"   # 'hello world'
"hello" * 3               # 'hellohellohello'

字符串格式化

# f-string (推荐)
name = "Alice"
age = 25
print(f"My name is {name}, age {age}")

# 格式化数值
pi = 3.14159
print(f"Pi = {pi:.2f}")    # Pi = 3.14

# format 方法
"{}, {}".format("hello", "world")
"{1} {0}".format("world", "hello")

常用字符串方法

s = "  Hello, World!  "

# 大小写转换
s.upper()          # '  HELLO, WORLD!  '
s.lower()          # '  hello, world!  '
s.title()          # '  Hello, World!  '

# 去除空白
s.strip()          # 'Hello, World!'
s.lstrip()         # 'Hello, World!  '
s.rstrip()         # '  Hello, World!'

# 查找替换
s.find("World")    # 9  返回索引,未找到返回 -1
s.replace("World", "Python")  # '  Hello, Python!  '

# 分割合并
"a,b,c".split(",")  # ['a', 'b', 'c']
",".join(['a', 'b', 'c'])  # 'a,b,c'

# 判断
s.startswith("He")  # True
s.endswith("!")     # True
s.isdigit()        # False

字符串切片

s = "Hello, World!"

# 基本切片
s[0]        # 'H'       第1个字符
s[-1]       # '!'       最后一个字符
s[0:5]      # 'Hello'   切片 [start:end)
s[::2]      # 'Hlo,Wrd' 步长为2
s[::-1]     # '!dlroW ,olleH' 反转

快速对照表

操作 示例 结果
类型判断 type(x) <class 'int'>
转字符串 str(123) '123'
转整数 int("123") 123
转浮点 float("3.14") 3.14
字符串长度 len("hello") 5
格式化 f"{x=}" 'x=10'

掌握这些基础,你就可以开始编写简单的 Python 程序了。