最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python基礎(chǔ)指南之字符串查找與替換的常用方法詳解

 更新時(shí)間:2026年06月08日 08:52:42   作者:星河耀銀海  
Python的字符串有40多個(gè)內(nèi)置方法,主要可以分為查找與替換(本文),分割與拼接和大小寫與判斷,其中查找和替換是大家最常用的操作,下面小編就和大家詳細(xì)講講吧

一、開篇:字符串方法的魅力

今天開始,我們要進(jìn)入字符串方法的世界——那些幫你在字符串中查找內(nèi)容、替換內(nèi)容、判斷內(nèi)容的強(qiáng)大工具。

Python的字符串有40多個(gè)內(nèi)置方法。別被這個(gè)數(shù)字嚇到——日常開發(fā)中真正高頻使用的大概15個(gè)左右。我將它們分成三組來(lái)講:查找與替換(本文)、分割與拼接、大小寫與判斷。

查找和替換是你處理文本時(shí)最常用的操作——從一段文字中找關(guān)鍵詞、替換模板中的占位符、提取特定格式的數(shù)據(jù),全都離不開它們。

二、find() 和 rfind():查找子串位置

2.1 find() 基本用法

find() 在字符串中查找子串,返回第一次出現(xiàn)的位置索引。如果找不到,返回 -1(而不是報(bào)錯(cuò))。

text = 'Python is easy, Python is powerful'

# 查找子串
print(text.find('Python'))     # 0(第一次出現(xiàn)的位置)
print(text.find('is'))         # 7
print(text.find('Java'))       # -1(沒找到)

# 指定查找范圍:find(sub, start, end)
print(text.find('Python', 10))    # 17(從索引10開始找)
print(text.find('Python', 0, 10)) # -1(在0到10范圍內(nèi)沒找到)

2.2 rfind():從右邊開始查找

text = 'Python is easy, Python is powerful'

# rfind:找最后一次出現(xiàn)的位置
print(text.rfind('Python'))   # 17
print(text.rfind('is'))       # 22(第二個(gè)'is')
print(text.find('is'))        # 7(第一個(gè)'is')

2.3 find() 實(shí)戰(zhàn)應(yīng)用

# 提取文件擴(kuò)展名
def get_file_extension(filename):
    dot_index = filename.rfind('.')
    if dot_index == -1:
        return ''  # 沒有擴(kuò)展名
    return filename[dot_index:]

print(get_file_extension('report.pdf'))   # .pdf
print(get_file_extension('archive.tar.gz')) # .gz
print(get_file_extension('README'))       # ''


# 提取URL中的協(xié)議
def get_url_protocol(url):
    separator = url.find('://')
    if separator == -1:
        return 'unknown'
    return url[:separator]

print(get_url_protocol('https://example.com'))  # https
print(get_url_protocol('ftp://files.server'))   # ftp


# 查找所有出現(xiàn)的位置
def find_all_occurrences(text, substring):
    """查找子串在文本中出現(xiàn)的所有位置"""
    positions = []
    start = 0
    while True:
        pos = text.find(substring, start)
        if pos == -1:
            break
        positions.append(pos)
        start = pos + 1
    return positions

text = 'abababab'
print(find_all_occurrences(text, 'ab'))  # [0, 2, 4, 6]

三、index() 和 rindex():查找但報(bào)錯(cuò)

find() 幾乎一樣,唯一的區(qū)別是:找不到時(shí)拋出 ValueError 而不是返回 -1。

text = 'Python編程'

# 找到了——行為完全一樣
print(text.index('Python'))  # 0
print(text.index('編程'))     # 6

# 區(qū)別:找不到時(shí)報(bào)錯(cuò)
# print(text.index('Java'))  # ValueError: substring not found

# 安全的用法——用try-except包裹
def safe_index(text, substring):
    try:
        return text.index(substring)
    except ValueError:
        return -1

print(safe_index('Python', 'Java'))  # -1

選擇 find() 還是 index()

  • 大多數(shù)情況用 find():更安全,返回-1即可判斷
  • 當(dāng)子串必須存在時(shí)用 index():找不到說(shuō)明數(shù)據(jù)有問題,報(bào)錯(cuò)比靜默失敗更好

四、count():統(tǒng)計(jì)出現(xiàn)次數(shù)

text = 'banana'

print(text.count('a'))      # 3
print(text.count('na'))     # 2
print(text.count('z'))      # 0

# 指定范圍統(tǒng)計(jì)
print(text.count('a', 3))       # 2(從索引3開始統(tǒng)計(jì))
print(text.count('a', 0, 3))    # 1(在0到3范圍內(nèi)統(tǒng)計(jì))

# 實(shí)際應(yīng)用
def count_keywords(text, keywords):
    """統(tǒng)計(jì)文本中各個(gè)關(guān)鍵詞出現(xiàn)的次數(shù)"""
    result = {}
    for keyword in keywords:
        result[keyword] = text.lower().count(keyword.lower())
    return result

article = """
Python是一種解釋型語(yǔ)言。Python的設(shè)計(jì)哲學(xué)強(qiáng)調(diào)代碼的可讀性。
Python支持多種編程范式,包括面向?qū)ο蠛秃瘮?shù)式編程。
"""
word_counts = count_keywords(article, ['Python', '編程', '語(yǔ)言'])
print(word_counts)
# {'Python': 3, '編程': 2, '語(yǔ)言': 1}

五、startswith() 和 endswith():首尾判斷

5.1 基本用法

filename = 'report_2024.pdf'

print(filename.startswith('report'))  # True
print(filename.endswith('.pdf'))      # True
print(filename.endswith('.txt'))      # False

# 可以傳入元組來(lái)匹配多個(gè)選項(xiàng)
print(filename.endswith(('.pdf', '.doc', '.docx')))  # True
print(filename.endswith(('.jpg', '.png', '.gif')))   # False

5.2 指定查找范圍

text = 'Python Programming'

# startswith可以帶start和end參數(shù)
print(text.startswith('Pro', 7))         # True(從索引7開始看)
print(text.startswith('Pro', 7, 10))     # True

# endswith也有范圍參數(shù)(檢查指定范圍內(nèi)的結(jié)尾)
print(text.endswith('ing', 0, 17))       # True(檢查text[0:17]的結(jié)尾)

5.3 實(shí)戰(zhàn)應(yīng)用

# 過(guò)濾文件列表
def filter_files_by_extension(files, extensions):
    """過(guò)濾出指定擴(kuò)展名的文件"""
    return [f for f in files if f.lower().endswith(extensions)]

files = ['data.csv', 'report.pdf', 'photo.jpg', 'script.py', 'notes.txt']
csv_and_py = filter_files_by_extension(files, ('.csv', '.py'))
print(csv_and_py)  # ['data.csv', 'script.py']


# 按前綴分類
def categorize_by_prefix(items, prefix_map):
    """根據(jù)前綴對(duì)項(xiàng)目分類"""
    categories = {key: [] for key in prefix_map}
    categories['other'] = []

    for item in items:
        categorized = False
        for prefix, category in prefix_map.items():
            if item.startswith(prefix):
                categories[category].append(item)
                categorized = True
                break
        if not categorized:
            categories['other'].append(item)

    return categories

files = ['img_001.jpg', 'doc_report.pdf', 'img_002.png', 'doc_notes.txt']
prefix_map = {'img_': 'images', 'doc_': 'documents'}
print(categorize_by_prefix(files, prefix_map))
# {'images': ['img_001.jpg', 'img_002.png'],
#  'documents': ['doc_report.pdf', 'doc_notes.txt'],
#  'other': []}

六、replace():替換內(nèi)容

6.1 基本用法

text = 'Hello, World! World is beautiful.'

# 基本替換
print(text.replace('World', 'Python'))
# Hello, Python! Python is beautiful.

# 限制替換次數(shù)
print(text.replace('World', 'Python', 1))
# Hello, Python! World is beautiful.(只替換第一個(gè))

# 刪除內(nèi)容(替換為空字符串)
print(text.replace('World', ''))
# Hello, !  is beautiful.
# (注意:多了空格,可能需要額外處理)

# 替換不存在的子串——靜默返回原字符串
print(text.replace('Java', 'Python'))  # 原樣返回

6.2 replace() 的高級(jí)應(yīng)用

# 清理文本中的多余空白
def clean_whitespace(text):
    """將連續(xù)的空白字符替換為單個(gè)空格"""
    import re
    # replace處理簡(jiǎn)單場(chǎng)景
    text = text.replace('\t', ' ').replace('\n', ' ')
    # 連續(xù)的多個(gè)空格替換為單個(gè)空格
    while '  ' in text:
        text = text.replace('  ', ' ')
    return text.strip()

raw_text = 'Hello    world\t\tPython   \n\n   編程'
print(clean_whitespace(raw_text))  # Hello world Python 編程


# 模板替換
def fill_template(template, **kwargs):
    """用字典的值填充模板中的占位符"""
    result = template
    for key, value in kwargs.items():
        placeholder = '{' + key + '}'
        result = result.replace(placeholder, str(value))
    return result

template = '尊敬的{name},您的訂單{order_id}已{status}。'
message = fill_template(
    template,
    name='小明',
    order_id='20240530001',
    status='發(fā)貨'
)
print(message)  # 尊敬的小明,您的訂單20240530001已發(fā)貨。


# replace的鏈?zhǔn)秸{(diào)用
text = 'a b c d e'
result = text.replace('a', '1').replace('b', '2').replace('c', '3')
print(result)  # 1 2 3 d e


# 多組替換——使用字典
def multi_replace(text, replacements):
    """一次性執(zhí)行多組替換"""
    for old, new in replacements.items():
        text = text.replace(old, new)
    return text

replace_map = {
    '&': '&',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
}
html_text = '<div class="content">Hello & Welcome</div>'
escaped = multi_replace(html_text, replace_map)
print(escaped)

七、translate() 和 maketrans():批量字符映射

對(duì)于單字符的批量替換,translate() 比多次調(diào)用 replace() 高效得多:

# 創(chuàng)建字符映射表
# str.maketrans(x, y, z)
# x: 要被替換的字符
# y: 替換成的字符(與x逐一對(duì)應(yīng))
# z: 要?jiǎng)h除的字符(可選)

# 凱撒密碼——每個(gè)字母后移3位
import string
lowercase = string.ascii_lowercase  # 'abcdefghijklmnopqrstuvwxyz'
shifted = lowercase[3:] + lowercase[:3]  # 'defghijklmnopqrstuvwxyzabc'
translation_table = str.maketrans(lowercase + lowercase.upper(),
                                   shifted + shifted.upper())

message = 'Hello, Python!'
encrypted = message.translate(translation_table)
print(encrypted)  # Khoor, Sbwkrq!


# 刪除所有數(shù)字和標(biāo)點(diǎn)符號(hào)
text = '你好,Python3!這是一個(gè)測(cè)試2024。'
# 方法1:刪除特定字符
digits_and_punctuation = '0123456789,。?。?、:;""''()'
translator = str.maketrans('', '', digits_and_punctuation)
cleaned = text.translate(translator)
print(cleaned)  # 你好Python這是一個(gè)測(cè)試


# 使用translate做簡(jiǎn)單的文本消毒
def sanitize_filename(filename):
    """清理文件名中的非法字符"""
    illegal_chars = r'<>:"/\|?*'
    translator = str.maketrans(illegal_chars, '_' * len(illegal_chars))
    return filename.translate(translator)

print(sanitize_filename('report:2024/05/30.pdf'))
# report_2024_05_30.pdf

什么時(shí)候用 translate() 而不是 replace()?

  • 單字符→單字符的批量映射:translate() 快得多
  • 多字符子串→多字符子串:只能用 replace()

八、strip()系列:去除首尾字符

8.1 strip() / lstrip() / rstrip()

# strip():去除首尾的空白字符(默認(rèn))
text = '   Hello, World!   \n'
print(repr(text.strip()))  # 'Hello, World!'

# 去除指定的字符(不是子串,是字符集合?。?
text = '###Hello, World!###'
print(text.strip('#'))     # 'Hello, World!'

text = 'www.example.com'
print(text.strip('w.moc'))  # 'example'
# 注意:strip('w.moc')是一直去除首尾出現(xiàn)的w、.、m、o、c這些字符
# 直到首尾不再出現(xiàn)這些字符為止

# lstrip():只去除左側(cè)
text = '   Hello   '
print(repr(text.lstrip()))  # 'Hello   '

# rstrip():只去除右側(cè)
text = '   Hello   '
print(repr(text.rstrip()))  # '   Hello'

8.2 strip() 實(shí)戰(zhàn)案例

# 清理用戶輸入
def clean_user_input(text):
    """清理用戶輸入的首尾空白和特殊符號(hào)"""
    return text.strip().strip('.,;:!?。,;:???')


inputs = ['   小明   ', '小紅。。。', '  小剛,,,   ', ',小麗。']
for inp in inputs:
    print(repr(clean_user_input(inp)))
# '小明'
# '小紅'
# '小剛'
# '小麗'


# 讀取配置文件中的值,去除注釋和空白
def parse_config_line(line):
    """解析配置文件的一行"""
    # 去除注釋(#后面的內(nèi)容)
    comment_index = line.find('#')
    if comment_index != -1:
        line = line[:comment_index]

    # 去除首尾空白
    return line.strip()


config_lines = [
    'server = localhost  # 數(shù)據(jù)庫(kù)服務(wù)器地址',
    'port = 3306         # 數(shù)據(jù)庫(kù)端口',
    'username = admin',
    ''
]
for line in config_lines:
    result = parse_config_line(line)
    if result:
        print(f'解析:{result}')

九、replace() vs re.sub():何時(shí)用正則

replace() 只能替換確定的字符串。如果需要模式匹配(如"所有數(shù)字"、“郵箱地址”),就需要正則表達(dá)式:

import re

text = '我的電話是138-1234-5678,他的電話是139-8765-4321。'

# replace做不到——每次號(hào)碼都不一樣
# 用正則表達(dá)式
masked = re.sub(r'\d{3}-\d{4}-\d{4}', '***-****-****', text)
print(masked)  # 我的電話是***-****-****,他的電話是***-****-****。


# replace能做到——不需要正則
text = 'Hello, WORLD! Hello, world!'
print(text.replace('Hello', 'Hi'))  # Hi, WORLD! Hi, world!

# replace做不到——大小寫不敏感的替換
print(re.sub('hello', 'Hi', text, flags=re.IGNORECASE))  # Hi, WORLD! Hi, world!

原則:能用 replace() 解決的就用 replace(),簡(jiǎn)單清晰;需要模式匹配時(shí)才用正則。

十、查找與替換的性能對(duì)比

import time

text = 'a' * 10000 + 'target' + 'a' * 10000

# find 比 in 更靈活(可以指定位置)
start = time.perf_counter()
pos = text.find('target')
elapsed = time.perf_counter() - start
print(f'find: {elapsed:.8f}秒, 位置={pos}')

# count 和 find 性能差不多
start = time.perf_counter()
cnt = text.count('a')
elapsed = time.perf_counter() - start
print(f'count: {elapsed:.8f}秒, 數(shù)量={cnt}')

# replace vs translate(字符替換場(chǎng)景)
chars_to_replace = 'abcdefghijklmnopqrstuvwxyz'
chars_replacement = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

# replace方式
start = time.perf_counter()
result1 = text
for old, new in zip(chars_to_replace, chars_replacement):
    result1 = result1.replace(old, new)
elapsed_replace = time.perf_counter() - start
print(f'replace: {elapsed_replace:.4f}秒')

# translate方式
start = time.perf_counter()
table = str.maketrans(chars_to_replace, chars_replacement)
result2 = text.translate(table)
elapsed_translate = time.perf_counter() - start
print(f'translate: {elapsed_translate:.4f}秒')
# translate快很多倍!

十一、本篇小結(jié)

字符串查找與替換方法速查:

方法功能找不到時(shí)
find()查找子串位置返回-1
rfind()從右查找返回-1
index()查找子串位置報(bào)ValueError
rindex()從右查找報(bào)ValueError
count()統(tǒng)計(jì)出現(xiàn)次數(shù)返回0
startswith()判斷開頭返回False
endswith()判斷結(jié)尾返回False
replace()替換子串返回原字符串
translate()批量字符映射N/A
strip()去除首尾字符可能返回空串

這些方法構(gòu)成了Python字符串處理的基礎(chǔ)。日常開發(fā)中,find() + replace() + strip() + startswith()/endswith() 這幾個(gè)占了我90%的字符串查找替換操作。下一篇我們學(xué)習(xí)分割與拼接——處理CSV、日志、路徑等結(jié)構(gòu)化文本的核心技能。

以上就是Python基礎(chǔ)指南之字符串查找與替換的常用方法詳解的詳細(xì)內(nèi)容,更多關(guān)于Python字符串查找與替換的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python?rsa和Crypto.PublicKey.RSA?模塊詳解

    python?rsa和Crypto.PublicKey.RSA?模塊詳解

    這篇文章主要介紹了python?rsa和Crypto.PublicKey.RSA?模塊,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-04-04
  • Python實(shí)現(xiàn)刪除Excel表格中重復(fù)行的實(shí)用方法

    Python實(shí)現(xiàn)刪除Excel表格中重復(fù)行的實(shí)用方法

    在整理客戶名單、導(dǎo)入調(diào)查數(shù)據(jù)或合并多個(gè)數(shù)據(jù)源時(shí),Excel?表格中很容易出現(xiàn)重復(fù)記錄,本文將介紹?4?種刪除?Excel?重復(fù)行的方法,大家可以根據(jù)需要進(jìn)行選擇
    2026-03-03
  • 使用Python來(lái)開發(fā)Markdown腳本擴(kuò)展的實(shí)例分享

    使用Python來(lái)開發(fā)Markdown腳本擴(kuò)展的實(shí)例分享

    這篇文章主要介紹了使用Python來(lái)開發(fā)Markdown腳本擴(kuò)展的實(shí)例分享,文中的示例是用來(lái)簡(jiǎn)單地轉(zhuǎn)換文檔結(jié)構(gòu),主要為了體現(xiàn)一個(gè)思路,需要的朋友可以參考下
    2016-03-03
  • 詳解python中讀取和查看圖片的6種方法

    詳解python中讀取和查看圖片的6種方法

    本文主要介紹了詳解python中讀取和查看圖片的6種方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-04-04
  • Python實(shí)現(xiàn)CSV轉(zhuǎn)TXT格式(單文件+批量處理)

    Python實(shí)現(xiàn)CSV轉(zhuǎn)TXT格式(單文件+批量處理)

    CSV格式因結(jié)構(gòu)簡(jiǎn)潔、易與表格軟件兼容而被廣泛使用,但TXT格式具有更強(qiáng)的通用性、更低的存儲(chǔ)冗余,下面我們就來(lái)看看如何使用Python實(shí)現(xiàn)二者的轉(zhuǎn)換吧
    2026-01-01
  • 使用pycharm和pylint檢查python代碼規(guī)范操作

    使用pycharm和pylint檢查python代碼規(guī)范操作

    這篇文章主要介紹了使用pycharm和pylint檢查python代碼規(guī)范操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-06-06
  • vscode配置anaconda3的方法步驟

    vscode配置anaconda3的方法步驟

    這篇文章主要介紹了vscode配置anaconda3的方法步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • 淺談pandas中DataFrame關(guān)于顯示值省略的解決方法

    淺談pandas中DataFrame關(guān)于顯示值省略的解決方法

    下面小編就為大家分享一篇淺談pandas中DataFrame關(guān)于顯示值省略的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-04-04
  • python中引用與復(fù)制用法實(shí)例分析

    python中引用與復(fù)制用法實(shí)例分析

    這篇文章主要介紹了python中引用與復(fù)制用法,以實(shí)例形式詳細(xì)分析了python中引用與復(fù)制的功能與相關(guān)使用技巧,需要的朋友可以參考下
    2015-06-06
  • 使用Python pip怎么升級(jí)pip

    使用Python pip怎么升級(jí)pip

    這篇文章主要介紹了使用Python pip怎么升級(jí)pip,本文給大家分享方法和實(shí)現(xiàn)步驟對(duì)python pip升級(jí)pip相關(guān)知識(shí)感興趣的朋友跟隨小編一起看看吧
    2020-08-08

最新評(píng)論

武城县| 沛县| 光山县| 裕民县| 明星| 宝应县| 湄潭县| 科技| 和平区| 卓资县| 彩票| 凉城县| 怀柔区| 台南县| 南宫市| 同德县| 南投县| 拜城县| 巴南区| 蕲春县| 镇江市| 元氏县| 达州市| 高安市| 阿拉善左旗| 迁西县| 荥经县| 赣州市| 海林市| 德格县| 东乌珠穆沁旗| 临安市| 库车县| 确山县| 清苑县| 万宁市| 微博| 安岳县| 青州市| 永登县| 平遥县|