简体   繁体   English

替换字符串中的单个字符

[英]Replace a single character in a string

I am trying to make a function that automatically generated a response to a selection of an action in a text adventure game.我正在尝试制作一个功能,该功能会自动生成对文本冒险游戏中动作选择的响应。 My problem is that I have to replace every second '_' with ' '.我的问题是我必须用''替换每一秒'_'。 However I have tried everything I have though of and whenever I google the question the only solution I get is to use .replace().然而,我已经尝试了我所拥有的一切,每当我用谷歌搜索这个问题时,我得到的唯一解决方案就是使用 .replace()。 However .replace() replaces every instance of that character.但是 .replace() 替换该字符的每个实例。 Here is my code, could you please fix this for me and explain how you fixed it.这是我的代码,请您帮我解决这个问题并解释一下您是如何解决的。

example_actions = ['[1] Search desk', '[2] Search Cupboard', '[3] Search yard'

def response(avaliable_actions):
    for i in avaliable_actions:
        print(i, end=' ')
        x = avaliable_actions.index(i)
        avaliable_actions[x] = avaliable_actions[x][4:]
    
    avaliable_actions = ' '.join(avaliable_actions)
    avaliable_actions = avaliable_actions.lower()

    avaliable_actions = avaliable_actions.replace(' ', '_')
    avaliable_actions = list(avaliable_actions)
    count = 0
    for i in avaliable_actions:
        if count == 2:
            count = 0
            index = avaliable_actions.index(i)
            avaliable_actions[index] = ' '
        elif i == '_':
            count += 1
            

    avaliable_actions = ' '.join(avaliable_actions)
            
    print('\n\n' + str(avaliable_actions)) #error checking

Did I understand you correct, that you wanna produce something like this?我是否理解正确,您想要制作这样的东西?

this_is_a_test -> this is_a test or this_is a_test ? this_is_a_test -> this_is_a this is_a test还是this_is a_test

If so, adapt the following for your needs:如果是这样,请根据您的需要调整以下内容:

s = "this_is_just_a_test"

def replace_every_nth_char(string, char, replace, n):
    parts = string.split(char)
    result = ""
    for i, part in enumerate(parts):
        result += part
        if i % n == 0:
            result += replace
        else:
            result += char
    return ''.join(result)

res = replace_every_nth_char(s, "_", " ", 2)
print(s, "->", res)
# "this_is_just_a_test" -> "this is_just a_test"

Here's one approach:这是一种方法:

s = 'here_is_an_example_of_a_sentence'

tokens = s.split('_')
result = ' '.join('_'.join(tokens[i:i+2]) for i in range(0,len(tokens),2))
print(result)

The result:结果:

here_is an_example of_a sentence

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM