python常用函数
本文最后更新于45 天前,在知识的增长过程中难免会有错误的理解,如有您发现有错误或者有不同的见解请发送邮件到thelistenerofrain@163.com或者留言~

enumerate(nums)

🔹 基本语法

Python编辑for index, value in enumerate(iterable, start=0):
    # 使用 index 和 value
  • iterable:任何可迭代对象,比如 listtuplestr 等。
  • start(可选):索引起始值,默认是 0

🔹 举个例子 🌰

假设有一个列表:

Python编辑nums = ['apple', 'banana', 'cherry']

❌ 普通遍历(只有值):

Python编辑for fruit in nums:
    print(fruit)
# 输出:
# apple
# banana
# cherry

拿不到索引

✅ 使用 enumerate(既有索引,又有值):

Python编辑for i, fruit in enumerate(nums):
    print(i, fruit)
# 输出:
# 0 apple
# 1 banana
# 2 cherry

这里:

  • i 是索引(0, 1, 2)
  • fruit 是对应的元素(’apple’, ‘banana’, ‘cherry’)

🔹 改变起始索引

你可以让索引从 1 开始(比如生成序号):

Python编辑for i, fruit in enumerate(nums, start=1):
    print(f"{i}. {fruit}")
# 输出:
# 1. apple
# 2. banana
# 3. cherry

或者简写为:

Python编辑for i, fruit in enumerate(nums, 1):
    ...

🔹 底层原理(简单理解)

enumerate(nums) 返回的是一个 枚举对象(enumerate object),它每次迭代会生成一个 (index, value) 的元组。

你可以把它转成列表看看:

Python编辑nums = ['a', 'b', 'c']
print(list(enumerate(nums)))
# 输出: [(0, 'a'), (1, 'b'), (2, 'c')]

所以这行代码:

Python编辑for i, num in enumerate(nums):

本质上等价于:

Python编辑for pair in [(0, 'a'), (1, 'b'), (2, 'c')]:
    i, num = pair  # 元组解包

🔹 常见用途

场景示例
打印带序号的列表for i, item in enumerate(items, 1): print(f"{i}. {item}")
修改列表中满足条件的元素需要知道索引才能赋值
构建字典(索引→值)dict(enumerate(nums))
在算法中记录位置如找最大值的索引

✅ 示例:找出第一个负数的位置

Python编辑nums = [3, 7, -2, 5]
for i, num in enumerate(nums):
    if num < 0:
        print(f"第一个负数在索引 {i}")
        break
# 输出: 第一个负数在索引 2

🔹 注意事项

  1. 不要手动维护索引
    错误写法:Python编辑i = 0 for num in nums: print(i, num) i += 1→ 容易出错,也不 Pythonic。用 enumerate 更安全简洁。
  2. 如果你不需要索引,就别用 enumerate
    只需要值?直接 for x in nums: 就好。
  3. enumerate 不会修改原列表
    它只是提供一种“带索引的遍历方式”。

✅ 总结

特点说明
功能同时获取索引和元素值
返回值(index, value) 元组序列
默认起始索引0
是否改变原数据❌ 不会
推荐使用场景需要位置信息的循环

💡 记住一句话
“当你既想知道‘是什么’,又想知道‘在哪儿’时,就用 enumerate。”

replace

replace() 是 Python 中 字符串(str)对象的一个内置方法,用于 将字符串中的某些子串替换为新的子串。它是处理文本时最常用、最实用的函数之一。


📌 基本语法

Python编辑str.replace(old, new[, count])

参数说明:

参数类型说明
oldstr要被替换的子字符串
newstr用来替换的新字符串
countint(可选)最多替换前 count 次匹配,默认是 全部替换

✅ 返回一个新字符串,原字符串不会被修改(因为字符串在 Python 中是不可变的)。


🔍 基础示例

1. 全部替换

Python编辑s = "hello world"
new_s = s.replace("l", "L")
print(new_s)  # "heLLo worLd"

2. 限制替换次数

Python编辑s = "apple apple apple"
new_s = s.replace("apple", "orange", 2)
print(new_s)  # "orange orange apple"

3. 替换空格、特殊字符等

Python编辑s = "a-b-c-d"
s.replace("-", "")      # "abcd"
s.replace("-", ", ")    # "a, b, c, d"

⚠️ 重要特性与注意事项

✅ 1. 区分大小写

Python编辑"Hello".replace("h", "H")  # "Hello"(没变化,因为 'h' ≠ 'H')

✅ 2. 只替换完整匹配的子串

Python编辑"banana".replace("ana", "X")  # "bXna"(从左到右匹配,不重叠)

匹配是非重叠从左到右进行的。

✅ 3. 不会修改原字符串(返回新字符串)

Python编辑s = "cat"
s.replace("c", "b")
print(s)  # 仍然是 "cat"!
# 正确用法:
s = s.replace("c", "b")  # 需要重新赋值

✅ 4. 可以替换成空字符串(即删除)

Python编辑"hello!".replace("!", "")  # "hello"

✅ 5. 支持多字符替换

Python编辑"www.example.com".replace("www.", "")  # "example.com"

🛠 常见应用场景

场景 1:清理用户输入

Python编辑user_input = "  Hello World!  "
clean = user_input.replace(" ", "").lower()  # "helloworld!"

场景 2:格式转换

Python编辑phone = "123-456-7890"
digits = phone.replace("-", "")  # "1234567890"

场景 3:简单模板替换

Python编辑template = "Dear {name}, welcome!"
message = template.replace("{name}", "Alice")
# "Dear Alice, welcome!"

(更复杂的模板建议用 str.format() 或 f-string)

场景 4:删除所有换行符

Python编辑text = "Line1\nLine2\r\nLine3"
single_line = text.replace("\n", " ").replace("\r", "")

❌ 常见误区

误区 1:以为 replace() 能修改原字符串

Python编辑s = "test"
s.replace("t", "T")  # 返回 "TesT",但 s 仍是 "test"
print(s)  # "test" ❌

✅ 正确做法:接收返回值

Python编辑s = s.replace("t", "T")

误区 2:试图用 replace() 替换多种不同字符

Python编辑# 错误想法:一次替换多个不同字符
s.replace("a", "x").replace("b", "y").replace("c", "z")  # 可以,但繁琐

✅ 更高效方式(用 str.translate()):

Python编辑trans = str.maketrans("abc", "xyz")
s.translate(trans)

🔁 对比其他替换方式

方法适用场景示例
str.replace()简单子串替换"abc".replace("a", "A")
str.translate()多字符一对一映射(高效)见上
正则表达式 re.sub()复杂模式(如数字、通配符)re.sub(r'\d+', '#', "a123b") → "a#b"

✅ 一般情况下,优先使用 replace(),它简单、快、易读。


✅ 总结

  • replace(old, new, count) 是 字符串替换的首选方法
  • 区分大小写非重叠匹配返回新字符串
  • 常用于:删除字符、格式清洗、简单文本替换
  • 记住:字符串不可变,必须接收返回值!
Python编辑# 最佳实践模板
original = "some text"
modified = original.replace("old", "new")
感谢您的阅读,如有错误,欢迎留言
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
下一篇