You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现按指定次数重复字符串元音字符的问题求助

解决字符串元音重复指定次数的问题

你的代码存在几个关键问题,导致无法得到预期结果:

  • 变量命名冲突:循环中用vocales作为迭代变量,直接覆盖了之前定义的元音集合vocales = "aeiou",导致循环无法遍历所有元音。
  • 替换目标错误:sustituto = string*numero是把整个原字符串重复多次,而我们需要的是单个元音字符重复指定次数(比如把a变成aa)。
  • 逻辑漏洞:即使修正替换目标,直接对原字符串连续replace可能会出现意外重复替换,但这个问题在你当前的错误逻辑下还没暴露。

正确解法1:逐个字符处理(逻辑清晰,推荐)

遍历字符串的每个字符,判断是否为元音,是则重复指定次数后加入结果,否则直接保留:

def new_string(string, numero):
    # 包含大小写元音,根据需求可调整
    vocales = "aeiouAEIOU"
    result = []
    for char in string:
        if char in vocales:
            result.append(char * numero)
        else:
            result.append(char)
    return ''.join(result)

# 测试示例
print(new_string("Charleston", 2))  # 输出: Chaarleestoon
print(new_string("Charleston", 3))  # 输出: Chaaarleeeestooon

正确解法2:使用replace批量替换

先遍历所有元音,将每个元音替换为自身重复指定次数的字符串:

def new_string(string, numero):
    vocales = "aeiouAEIOU"
    for vowel in vocales:
        string = string.replace(vowel, vowel * numero)
    return string

# 测试示例
print(new_string("Charleston", 2))  # 输出: Chaarleestoon

内容的提问来源于stack exchange,提问作者Joana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 14:35:10