Home > OS >  How to replace the first n numbers of a specific character in a string
How to replace the first n numbers of a specific character in a string

Time:10-20

I’m new to computer science and really stuck on this question so any help would be great :).

Firstly I was given the following global variable:

 ARROWS = ‘<>^v’

The idea is to create a function that takes in a string and an integer (n). The function should then replace the first n number of characters with ‘X’. So far this is easy, however, the problem is that the characters should ONLY be replaced if it is a part of the global variable ARROWS. If it isn’t, it should not be modified but still counts as one of the n numbers. The following exemplifies what needs to be done:

 >>>function(‘>>.<>>...’, 4)
 ‘XX.X>>...’
 >>>function(‘>..>..>’, 6)
 ‘X..X..>’
 >>>function(‘..>>>.’, 2)
 ‘..>>>.’

Please help :)

CodePudding user response:

You can use the re module to match a regex set of your arrows.

import re
txt_to_replace = "aa^aaa<>aaa>"
x= re.sub(r'[<>^v]', 'X', txt_to_replace ,3 )
# x is now aaXaaaXXaaa>

CodePudding user response:

You can use re.sub() to replace any of the characters in ARROW.

To limit it to the first N characters of the input string, perform the replacement on a slice and concatenate that with the remainder of the input string.

import re

def replace_arrow(string, limit):
    arrows_regex = r'[<>^v]'
    first_n = string[:limit]
    rest = string[limit:]
    return re.sub(arrows_regex, 'X', first_n)   rest

CodePudding user response:

Hi it seems to me (if you want to avoid using libraries) that you can iterate over the characters in the string and do comparisons to decide if the character needs to be changed. Here is some sample code which should help you.

ARROWS = '<>^v'


def replace_up_to(in_str, n):
    # store the new character in this list
    result = []

    for i, char in enumerate(in_str):
        # decide if we need to change the char
        if i < n and char in ARROWS:
            result.append("X")
            continue

        result.append(char)

    # return a new string from our result list
    return "".join(result)

CodePudding user response:

The solution is very straightforward. Hope this helps. :)

ARROWS = "<>^v"
arrows_set = set(ARROWS)

def function(word, n):
    newWord = ""
    for i in range(0, len(word)):
        if word[i] in arrows_set and i < n:
            newWord  = 'X'
        else:
            newWord  = word[i]
        
    return newWord

print(function(">>.<>>...", 4))
print(function(">..>..>", 6))
  • Related