【问题标题】:How to replace a letter in a string?如何替换字符串中的字母?
【发布时间】:2020-04-11 03:17:13
【问题描述】:

我正在尝试解决斐波那契的兔子问题。通常,这个问题意味着兔子在“n”个月内的增长永远不会死亡。但现在,死在'm'个月。

我想模拟这种情况。因此,我创建了一个字典,其中包含每次更改的键和值。比如:

kbunny = {'a': 'b', 'b':'ca', 'c':'a'}

稍后,我想在一个名为 'gbunny' 的字符串中搜索每个键,并将该键替换为其值。

gbunny = 'a'
for key, val in zip(kbunny.keys(), kbunny.values()):
     for a, b in enumerate(gbunny):
          if b[a] is key:
               b[a] = b[a].replace(key, val)

但是,我不知道字符串在 python 中是不可变的。

我还有什么其他选择?

【问题讨论】:

    标签: python-3.x string replace


    【解决方案1】:

    您需要重新考虑您的方法。字符串确实是不可变的,但是您可以使用一些帮助列表来完成这项工作。

    每次我们从 gbunny 开始,使用字典来获取对应的值,并将其存储到一个列表中。将此列表转换为字符串,使用该字符串值刷新 gbunny,然后清除帮助列表,然后继续下一次迭代。

    须藤代码:

    kbunny = {'a': 'b', 'b':'ca', 'c':'a'}
    gbunny = 'a'
    # you can create helper list here or somewhere else, 
    # the location depends on how you want to handle the 'empty helper list' process
    
    # You want to set a max_interation number so the loop can exit 
    while max_iterations: 
        # use the kbunny to map each character in gbunny to its corresponding string and store in helper list 
        # convert helper list to string using ''.join()
        # pass the new string value to gbunny 
        # reset helper list to empty
        # decrease max_iterations by one 
        # continue to next iteration
    

    这听起来像是一个有趣的问题,我不想只给你解决方案。如果您有任何问题,请在下方评论。

    【讨论】:

    • 是的!这很有趣。它是 Python 生物信息学培训 Rosalind 项目的一部分。但是这个问题花了我三天的时间,我想完成它。谢谢。
    猜你喜欢
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 2023-03-23
    • 2014-09-03
    相关资源
    最近更新 更多