-1

Sorry if this has been asked before, but I've been struggling with this for weeks now.

I'm trying to figure out how to replace a particular substring within an arbitrary string with another particular substring.

IE:

If I get user to type in an arbitrary string, I want to replace any instance of "MAA" with something like "UOP".

My code:

cstring = input("Enter a character string: ")


for i in cstring:
    if ((i != 'M') and (i != 'U') and (i != 'I')):
        break
    else:
        if (cstring[-1] == 'I'):
            cstring = cstring + 'U'
        if (cstring[:1] == 'M'):
            cstring = cstring + cstring[1:]
        if ('III' in cstring):
            cstring = cstring[:i] + "U" + cstring[i:]
        if ('UU' in cstring):
            cstring = cstring[:i] + '' + cstring[i:]
        break
print(cstring)

Thanks!

Cody
  • 2,643
  • 2
  • 10
  • 24
  • as for why your code doesn't work, you have a `break` statement in both conditionals, so the for loop is forced to stop after the first iteration. – Tadhg McDonald-Jensen Aug 17 '16 at 22:21
  • As Tadhg has mentioned, don't use `break`, just use `continue`. This doesn't look like an assignment to me though, looks more like research/science code potentially for some kind of user-input based config or something. – Thtu Aug 17 '16 at 22:23
  • It's not an assignment question, but a tutorial one. I've been advised that the cstring.replace() method won't work for this, and that I should instead use slicing so as to maintain proper index conformity. – theGreatWhatever Aug 17 '16 at 22:28
  • Possible duplicate of [Replace part of a string in Python?](http://stackoverflow.com/questions/10037742/replace-part-of-a-string-in-python) – Tadhg McDonald-Jensen Aug 17 '16 at 22:28
  • But thanks for the break problem haha. I totally didn't notice that. – theGreatWhatever Aug 17 '16 at 22:28
  • This is based off the MU game out of "Godel, Escher, and Bach: an Eternal Golden Braid" by Douglas R Hofstadter – theGreatWhatever Aug 17 '16 at 22:31
  • `i` represents each character in the string so it can't be used for slicing, to keep an index and the character use [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate) like `for i, char in enumerate(cstring):` then keep a distinction between the index `i` and the character `char`. – Tadhg McDonald-Jensen Aug 17 '16 at 22:33

2 Answers2

0

You can use the String replace method like this:

cstring.replace("MAA,"UOP")

However, if you want to code it yourself, this works:

cstring = input("Enter a character string: ")


for i in range (0, len(cstring)):
    if (len(cstring[i:]) >= 3 and cstring[i] == "M" and cstring[i+1] == "A" and cstring[i+2] == "A"):
        cstring = cstring[:i] + "UOP" + cstring[i+3:]
print(cstring)
0

As other users have noted you can use str.replace. Here are some other options:

Regular Expressions

This is probably the way to go since you'll be able to replace any regex with your replacement string with all the advantages of the various re flags.

import re
re.sub("MAA", "UOP", cstring)

Validate String on Input

If your end goal is to work with a string with some simple replacements, you can also just try to enforce this in the input level. i.e.

cstring = input("Enter a valid character string: ")
while bool(re.search("invalid_characters_regex", cstring)):
    print("Your input contained invalid characters, please try again.")
    cstring = input("Enter a valid character string: ")
Thtu
  • 1,992
  • 15
  • 21