MST

星途 面试题库

面试题:Python复杂字符串特定位置正则匹配及替换

有字符串 'The price of product1 is $100, and the price of product2 is $200',从字符串第15个字符位置开始,用正则表达式匹配出价格(以$开头的数字),并将所有匹配到的价格增加10% 后替换回原字符串,用Python代码实现,并阐述实现思路和可能遇到的问题。
39.1万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 从字符串第15个字符位置开始截取子字符串。
  2. 使用正则表达式匹配出以$开头的数字,即价格。
  3. 将匹配到的价格提取出来并转换为浮点数,增加10%。
  4. 将增加后的价格替换回原字符串的相应位置。

可能遇到的问题

  1. 正则表达式匹配失败:可能由于正则表达式书写不正确,导致无法匹配到价格。
  2. 数据类型转换错误:在将价格从字符串转换为浮点数以及将增加后的价格转换回字符串时,可能会因为数据格式不符合要求而报错。
  3. 替换位置错误:在替换回原字符串时,要确保替换的位置准确,否则可能导致原字符串结构混乱。

Python代码实现

import re


def modify_price():
    s = 'The price of product1 is $100, and the price of product2 is $200'
    sub_str = s[15:]
    pattern = r'\$\d+'
    matches = re.findall(pattern, sub_str)
    for match in matches:
        price = float(match[1:])
        new_price = price * 1.1
        new_price_str = f'${new_price:.2f}'
        sub_str = sub_str.replace(match, new_price_str, 1)
    new_s = s[:15] + sub_str
    return new_s


print(modify_price())