Skip to content
Advertisement

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(). However .replace() replaces every instance of that character. 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('nn' + str(avaliable_actions)) #error checking

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement