溫馨提示×

Python中怎么用replace()替換復雜的字符串

小億
94
2024-04-02 14:07:05
欄目: 編程語言

要替換復雜的字符串,可以使用replace()方法結合正則表達式來實現。下面是一個示例代碼:

import re

def replace_complex_string(input_str):
    # 定義要替換的字符串模式
    pattern = r'(\d{4})-(\d{2})-(\d{2})'
    
    # 定義替換后的字符串模式
    replace_pattern = r'\3/\2/\1'
    
    # 使用re.sub()方法進行替換
    output_str = re.sub(pattern, replace_pattern, input_str)
    
    return output_str

input_str = "Today is 2022-01-01"
output_str = replace_complex_string(input_str)

print(output_str)

在這個示例中,我們定義了一個模式(\d{4})-(\d{2})-(\d{2})來匹配日期格式yyyy-mm-dd,然后定義了替換模式\3/\2/\1來將日期格式替換為dd/mm/yyyy。最后使用re.sub()方法進行替換操作。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女