0

I want to take a string and format it so that I can control the number of changes I make it it. For example..

"This is an awesome string" with replace method "@" for "a" would give me...

"this is @n @wesome string" But I want to say replace 1 "a" with "@" and leave the rest alone..

"This is @n awesome string" The placement is allowed to be random but whats important is I account for how many of a particular kind I replace. Any ideas?

3 Answers 3

1

The string replace function takes an optional count argument to control the maximum number of replacements to make

"This is an awesome string".replace("a","@")   # "This is @n @wesome string"

"This is an awesome string".replace("a","@",1) # "This is @n awesome string"

If you need to do it at random, we can write a function to do that

import random
def randreplace(str,c,c_replace,maxnum=0):
    if maxnum >= str.count(c) or maxnum<1:
        return str.replace(c,c_replace)
    indices = [i for i,x in enumerate(str) if x==c]
    replacements = random.sample(indices,maxnum)
    st_pieces = (x if not i in replacements else c_replace for i,x in enumerate(str))
    return "".join(st_pieces)

This function takes the string to do the replacements in, the character to replace, the character to replace it with, and the maximum number of replacements (0 for all of them) and returns the string with the desired number of replacements done at random.

random.seed(100)
randreplace("This is an awesome string","a","@",1) # "This is @n awesome string"
randreplace("This is an awesome string","a","@",1) # "This is an @wesome string"
randreplace("This is an awesome string","a","@",2) # "This is @n @wesome string"
randreplace("This is an awesome string","a","@")   # "This is @n @wesome string"
Sign up to request clarification or add additional context in comments.

5 Comments

Does it change the first one it comes to or is there any particular order to it? I was looking to make it random but I think I can make a workaround from this. Thanks!
Yes, it will replace the first occurrence.
@AndrewMayes You didn't specify initially that you needed it to be random, only that it was allowed to be random. I have added a function that will make the replacements random.
Okay yes that is what I needed!
@AndrewMayes Glad to help. If this solves your problem, please consider accepting the answer.
1

The following function would let you change a single matching character:

def replace_a_char(text, x, y, n):
    matched = 0
    for index, c in enumerate(text):
        if c == x:
            matched += 1
            if matched == n:
                return text[:index] + y + text[index+1:]

    return text

text = "This is an awesome string and has lot of characters"

for n in xrange(1, 10):
    print replace_a_char(text, 'a', '@', n)

Giving you the following output:

This is @n awesome string and has lot of characters
This is an @wesome string and has lot of characters
This is an awesome string @nd has lot of characters
This is an awesome string and h@s lot of characters
This is an awesome string and has lot of ch@racters
This is an awesome string and has lot of char@cters
This is an awesome string and has lot of characters
This is an awesome string and has lot of characters
This is an awesome string and has lot of characters

2 Comments

Would this work too if I changed "n" to a different number?
Or wait not "n" but the amount I wanted to match like 2 or 3 "@"s?
1

@Andrew Mayes says, "I was looking to make it random ..."

import random

target = "a"

replacement = "@"

string = "This is an awesome string"

indicies = [index for index, character in enumerate(string) if character == target]

index = random.choice(indicies)

string = string[:index] + replacement + string[index + 1:]

Let's turn this into a function that takes a choice of how many random replacements to make and returns both the modified string and the actual number of replacements made (e.g. you might request too many.)

def random_replace(string, target, replacement, instances):
    indicies = [index for index, character in enumerate(string) if character == target]

    replacements = min(instances, len(indicies))

    random_indicies = random.sample(indicies, replacements)

    for index in random_indicies:
        string = string[:index] + replacement + string[index + 1:]

    return string, replacements

Some usage examples:

>>> print(random_replace(string, "a", "@", 3))
('This is @n awesome string @nd has lot of char@cters', 3)
>>> print(random_replace(string, "a", "@", 10))
('This is @n @wesome string @nd h@s lot of ch@r@cters', 6)
>>> print(random_replace(string, "a", "@", 0))
('This is an awesome string and has lot of characters', 0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.