前端开发 0 基础学 Python 入门指南:数字与字符串篇

一、Python 中的数字类型

1.1 三种数字类型详解

Python 有三种数字类型,比 JavaScript 更加明确和强大:

# 1️⃣ 整数 (int) - 没有大小限制!
age = 25
count = -100
big_number = 1_000_000_000  # 可以用下划线分隔,提高可读性
huge = 10 ** 100  # Python 整数可以无限大!

print(f"年龄: {age}, 类型: {type(age)}")  # <class 'int'>

# 2️⃣ 浮点数 (float) - 小数
price = 19.99
temperature = -3.5
scientific = 1.5e-3  # 科学计数法: 0.0015

print(f"价格: {price}, 类型: {type(price)}")  # <class 'float'>

# 3️⃣ 复数 (complex) - 科学计算用
c1 = 3 + 4j  # j 表示虚部(数学中的 i)
c2 = complex(2, -1)  # 2 - 1j

print(f"复数: {c1}")
print(f"实部: {c1.real}, 虚部: {c1.imag}")

1.2 数字类型对比表

类型PythonJavaScript说明
整数intNumberPython 整数无大小限制
浮点数floatNumber都有精度问题
复数complexPython 原生支持,JS 需要库
大整数intBigIntPython 自动处理,JS 需显式声明

1.3 浮点数精度问题

️ Python 和 JavaScript 都有浮点数精度问题:

# Python
result = 0.1 + 0.2
print(result)  # 0.30000000000000004
print(result == 0.3)  # False

#  解决方案1: 使用 round()
print(round(0.1 + 0.2, 2))  # 0.3

#  解决方案2: 使用 decimal 模块
from decimal import Decimal
precise = Decimal('0.1') + Decimal('0.2')
print(precise)  # 0.3
// JavaScript 同样的问题
console.log(0.1 + 0.2) // 0.30000000000000004
console.log((0.1 + 0.2).toFixed(2)) // "0.30"

二、类型转换

2.1 数字之间的转换

# 整数 → 浮点数
x = 10
print(float(x))  # 10.0

# 浮点数 → 整数(截断小数部分)
y = 3.14
print(int(y))  # 3

# 数字 → 复数
print(complex(5))  # (5+0j)

2.2 字符串与数字互转

# 字符串 → 数字
num_str = "123"
print(int(num_str))  # 123
print(float("45.67"))  # 45.67

# 数字 → 字符串
print(str(100))  # "100"
print(str(3.14))  # "3.14"

# ️ 注意:不能直接转换格式不对的字符串
try:
    int("3.14")  #  报错!ValueError
except ValueError:
    print("正确方式: int(float('3.14'))")
    print(int(float("3.14")))  #  先转 float,再转 int

2.3 类型转换对比

操作PythonJavaScript
字符串转整数int("123")parseInt("123")
字符串转浮点数float("3.14")parseFloat("3.14")
数字转字符串str(123)String(123)`${123}`
错误处理抛出 ValueError返回 NaN

关键区别: Python 转换失败会报错,JavaScript 返回 NaN


三、类型判断

3.1 两种判断方式

value = 42

# 方式1: type() 函数
print(type(value))  # <class 'int'>
print(type(value) == int)  # True

# 方式2: isinstance() 函数(推荐)
print(isinstance(value, int))  # True
print(isinstance(value, (int, float)))  # 可以检查多个类型,True

3.2 判断是否为数字

def is_number(value):
    """判断是否为数字类型"""
    return isinstance(value, (int, float, complex))

# 测试
print(is_number(42))      # True
print(is_number(3.14))    # True
print(is_number("123"))   # False
print(is_number(2+3j))    # True

3.3 类型判断对比

# Python
isinstance(42, int)  # True
type(42) == int      # True
// JavaScript
typeof 42 === 'number' // true
Number.isInteger(42) // true

四、何时使用数字 vs 字符串

4.1 使用规则表

场景类型原因示例
需要计算数字加减乘除、比较大小价格、年龄、数量
不需要计算字符串仅用于显示、存储电话号码、身份证号
有前导零字符串数字会丢失前导零邮政编码 "010001"
编号/代码字符串可能包含字母、特殊字符订单号、产品编号
统计计算数字求和、平均、排序成绩、销量

4.2 实例对比

#  错误示例:电话号码用数字
phone_wrong = 13800138000
# 问题1: 如果是 01088888888,前导0会丢失
# 问题2: 无法添加分隔符如 "-"

#  正确示例:电话号码用字符串
phone_correct = "010-88888888"

#  价格用数字(需要计算)
price1 = 19.99
price2 = 29.99
total = price1 + price2  # 49.98 

#  价格用字符串(会拼接!)
price_str1 = "19.99"
price_str2 = "29.99"
result = price_str1 + price_str2  # "19.9929.99" 

JavaScript 同样的规则:

//  正确
let phone = '010-88888888'
let price = 19.99

//  错误
let phone = 13800138000 // 前导0会丢失

五、字符串大小比较

5.1 Python 字符串比较规则

按字典序(Unicode 码点)逐字符比较:

# 基本比较
print('abc' < 'abd')  # True
print('apple' < 'banana')  # True

# ️ 数字字符串比较(注意陷阱!)
print('100' < '20')  # True(字符串比较,'1' < '2')
print('100' < '2')   # True('1' < '2')
print(100 < 20)      # False(数字比较)

# 大小写敏感
print('Apple' < 'banana')  # True(大写字母 ASCII 码更小)
print('a' < 'A')  # False(小写字母 ASCII 码更大)
print(f"ord('A')={ord('A')}, ord('a')={ord('a')}")  # 65 vs 97

# 长度不同
print('abc' < 'abcd')  # True
print('abc' < 'ab')    # False

5.2 Python vs JavaScript 对比

特性PythonJavaScript说明
比较方式<, >, <=, >=<, >, <=, >=语法相同
比较规则Unicode 字典序Unicode 字典序规则相同
大小写区分区分都区分大小写
推荐方法直接用 <, >localeCompare() 方法JS 推荐用方法
# Python
print('apple' < 'banana')  # True
// JavaScript
console.log('apple' < 'banana') // true
console.log('apple'.localeCompare('banana')) // -1(推荐)

5.3 数字字符串排序

Python 和 JavaScript 的关键区别:

# Python - 字符串排序
nums_str = ['100', '20', '3']
print(sorted(nums_str))  # ['100', '20', '3']

# Python - 数字排序
nums_int = [100, 20, 3]
print(sorted(nums_int))  # [3, 20, 100]  直观!
// JavaScript - 字符串排序
let numsStr = ['100', '20', '3']
console.log(numsStr.sort()) // ['100', '20', '3']

// JavaScript - 数字排序(️ 陷阱!)
let numsInt = [100, 20, 3]
console.log(numsInt.sort()) // [100, 20, 3]  默认按字符串排序!

//  正确方式:提供比较函数
console.log(numsInt.sort((a, b) => a - b)) // [3, 20, 100]

总结: Python 数字排序更直观,JavaScript 需要额外提供比较函数!


六、字符串拼接与运算

6.1 字符串拼接(加法)

# 方式1: 使用 + 号
str1 = "Hello"
str2 = "World"
print(str1 + " " + str2)  # "Hello World"

# 方式2: f-string(推荐)
name = "张三"
age = 25
print(f"{name}今年{age}岁")  # "张三今年25岁"

# 方式3: format() 方法
print("{}今年{}岁".format(name, age))

# 方式4: % 格式化(旧式)
print("%s今年%d岁" % (name, age))

对比 JavaScript:

// JavaScript
let str1 = 'Hello'
let str2 = 'World'
console.log(str1 + ' ' + str2) // "Hello World"

// 模板字符串(类似 Python 的 f-string)
let name = '张三'
let age = 25
console.log(`${name}今年${age}岁`) // "张三今年25岁"

6.2 字符串重复(乘法)

Python 独有特性:

# 字符串重复
print("Ha" * 3)    # "HaHaHa"
print("-" * 20)    # "--------------------"
print("" * 5)    # ""

# 实用场景:创建分隔线
print("=" * 50)

JavaScript 需要使用方法:

// JavaScript
console.log('Ha'.repeat(3)) // "HaHaHa"
console.log('-'.repeat(20)) // "--------------------"

6.3 字符串长度 - len()

# Python 使用 len() 函数
text1 = "Hello"
text2 = "你好世界"
text3 = "Hello你好"
empty = ""

print(len(text1))  # 5
print(len(text2))  # 4(中文也是1个字符)
print(len(text3))  # 7
print(len(empty))  # 0

# len() 统计字符数,不是字节数
print(len(text2.encode('utf-8')))  # 12(UTF-8 字节数)

对比 JavaScript:

// JavaScript 使用 .length 属性
let text1 = 'Hello'
let text2 = '你好世界'

console.log(text1.length) // 5
console.log(text2.length) // 4

6.4 字符串操作对比表

操作PythonJavaScript
获取长度len(str)str.length
字符串拼接str1 + str2str1 + str2
字符串重复str * 3str.repeat(3)
格式化f"{var}"`${var}`

七、字符串和数字的加法运算

7.1 Python vs JavaScript 的重大区别

这是 Python 和 JavaScript 最大的区别之一!

# Python - 严格类型,不允许混合
num = 100
text = "200"

#  这会报错!
try:
    result = num + text
except TypeError as e:
    print(f" 错误: {e}")
    # TypeError: unsupported operand type(s) for +: 'int' and 'str'

#  必须显式转换
print(num + int(text))      # 300(数字相加)
print(str(num) + text)      # "100200"(字符串拼接)
// JavaScript - 自动类型转换
let num = 100
let text = '200'

console.log(num + text) // "100200"(️ 自动转为字符串!)
console.log(num + Number(text)) // 300
console.log(String(num) + text) // "100200"

7.2 对比表格

操作PythonJavaScript
数字 + 数字数学加法数学加法
字符串 + 字符串字符串拼接字符串拼接
数字 + 字符串 报错(TypeError) 字符串拼接
类型安全 严格,更安全️ 宽松,易出错

7.3 常见陷阱

# 陷阱1: input() 返回字符串
user_input = input("请输入一个数字: ")  # 假设输入 "10"
print(type(user_input))  # <class 'str'>

#  错误
# result = user_input + 5  # TypeError!

#  正确
result = int(user_input) + 5
print(result)  # 15

# 陷阱2: 字符串数字的比较
print('9' > '10')  # True(字符串比较!'9' > '1')
print(9 > 10)      # False(数字比较)

# 陷阱3: 列表拼接
list1 = [1, 2, 3]
list2 = [4, 5]
print(list1 + list2)  # [1, 2, 3, 4, 5](列表拼接)

JavaScript 的陷阱:

// 自动转换导致的混乱
console.log('5' + 3) // "53"(字符串拼接)
console.log('5' - 3) // 2(数学运算!)️
console.log('5' * 3) // 15(数学运算!)️

// Python 会在这些情况下都报错,更安全!

八、总结对比

8.1 数字类型总结

特性PythonJavaScript
整数类型int(无限大)Number/BigInt
浮点数floatNumber
复数complex(原生支持) 需要库
精度问题 有(同 JS)
类型转换int(), float(), str()parseInt(), parseFloat()
转换失败抛出异常返回 NaN

8.2 字符串操作总结

特性PythonJavaScript
拼接+ 或 f-string+ 或模板字符串
重复* 3.repeat(3)
长度len(str)str.length
比较<, ><, >.localeCompare()
类型混合 严格禁止 自动转换

8.3 核心差异

特性PythonJavaScript
类型安全 严格,报错明确️ 宽松,自动转换
数字+字符串 TypeError 字符串拼接
数字排序 直接 sorted()️ 需要比较函数
哲学显式优于隐式灵活但易出错

最佳实践

9.1 类型转换要显式

#  好
result = int(input("输入数字: ")) + 10

#  不好(会报错)
# result = input("输入数字: ") + 10

9.2 使用 isinstance() 判断类型

value = 42
if isinstance(value, (int, float)):
    print("这是数字")

9.3 电话、编号用字符串

phone = "010-88888888"  # 
order_id = "ORD-2024-001"  # 
zip_code = "010001"  #  保留前导0

9.4 字符串格式化优先用 f-string

name = "Python"
age = 30
print(f"{name} 已经 {age} 岁了")  # 推荐

9.5 注意浮点数精度

# 金融计算使用 Decimal
from decimal import Decimal
price = Decimal('19.99')
quantity = Decimal('3')
total = price * quantity  # 精确计算

实战练习

创建一个购物车计算程序:

print("=== 购物车结算系统 ===n")

# 输入商品信息
product1 = input("商品1名称: ")
price1 = float(input("商品1价格: "))
quantity1 = int(input("商品1数量: "))

product2 = input("商品2名称: ")
price2 = float(input("商品2价格: "))
quantity2 = int(input("商品2数量: "))

# 计算
subtotal1 = price1 * quantity1
subtotal2 = price2 * quantity2
total = subtotal1 + subtotal2

# 输出
print("n=== 购物清单 ===")
print(f"{product1}: ¥{price1} × {quantity1} = ¥{subtotal1:.2f}")
print(f"{product2}: ¥{price2} × {quantity2} = ¥{subtotal2:.2f}")
print("-" * 40)
print(f"总计: ¥{total:.2f}")

# 类型检查
print(f"n类型验证:")
print(f"price1 是数字? {isinstance(price1, (int, float))}")
print(f"product1 是字符串? {isinstance(product1, str)}")

核心要点

  1. 数字类型

    • Python 有 int, float, complex 三种
    • 整数无大小限制(比 JS 强大)
    • 浮点数都有精度问题
  2. 类型转换

    • Python 严格,不自动转换
    • 转换失败会报错,不会返回 NaN
    • 使用 int(), float(), str() 显式转换
  3. 类型判断

    • isinstance() 判断(推荐)
    • type() 获取类型
  4. 使用规则

    • 需要计算 → 用数字
    • 不需要计算的"数字" → 用字符串
    • 电话、编号、邮编 → 字符串
  5. 字符串操作

    • + 拼接,* 重复
    • len() 获取长度
    • f-string 格式化(类似 JS 模板字符串)
  6. 关键区别

    • Python: 类型严格,显式转换
    • JavaScript: 类型宽松,自动转换
    • Python 哲学: 显式优于隐式

本文适合前端开发者快速掌握 Python 的数字和字符串操作,通过对比 JavaScript 理解两种语言的差异。

本站提供的所有下载资源均来自互联网,仅提供学习交流使用,版权归原作者所有。如需商业使用,请联系原作者获得授权。 如您发现有涉嫌侵权的内容,请联系我们 邮箱:[email protected]