0

I'm working on a script where I'm trying to create a list of strings that, at each subsequent character, have a sub for an input character.

my_replacement = input("Replacement character?: ")
orig_strng = ABCDEFGHIJKL
lst =[]
for i in range(len(orig_strng)):
    a = function to replace orig_strng[i] with my_replacements
    lst.append(a)

If my input is X, the appended lst output from each iteration would look like: XBCDEFGHIJKL, AXCDEFGHIJKL, ABXDEFGHIJKL, etc.

I get that strings themselves are immutable - so i can't directly edit them. How would I be able to tackle this in a python-ic way?

1
  • So you want to walk through you string with the input character? Commented Feb 17, 2016 at 18:04

5 Answers 5

2
def replace_each(s,letter):
    for i,original_letter in enumerate(s):
        yield "{0}{1}{2}".format(s[:i],letter,s[i+1:])

print(list(replace_each("ABCDEFGHI","x")))

is pretty pythonic I think

Sign up to request clarification or add additional context in comments.

Comments

1

You can convert the string into a list, perform the replacement, then convert it back into a string with join

def foo(my_string, i, replacement):
    my_list = list(my_string)
    my_list[i] = replacement
    return "".join(my_list)

foo(orig_strng, 1, "X")
#'AXCDEFGHIJKL'

Comments

0

The string method replace() works nicely here for the example case but not necessarily for all cases.

my_replacement = input("Replacement character?: ")
orig_strng = ABCDEFGHIJKL
lst =[]
for i in range(len(orig_strng)):
    a = orig_strng.replace(orig_string[i], my_replacement)
    lst.append(a)

If you wanted to, you could do this with a list comprehension:

a = [orig_string.replace(orig_string[i], my_replacement) for i in orig_string]

Comments

0

Is this what you mean?

def foo(string,i,replacement):
    return string[:i]+replacement+string[i+1:]

Comments

0

I find that translation tables and the translate function often come in handy. Like you said, strings are immutable, so the translate function returns a copy with the translation completed.

The example below allows you to input a replacement string (not just a single character), and it will replace all occurrences of the character(s) to be translated with the provided input character(s).

from string import maketrans

original = 'ABCDEFGHIJK'
n = len(original)
user_in = "XYZ" #can also just be a single character X
m = min(len(user_in), n)
for i in range(n):
    trans_table = maketrans((original[i:] + original[:i])[:m], user_in[:m])
    new = original.translate(trans_table)
    print new

Output

XYZDEFGHIJK
AXYZEFGHIJK
ABXYZFGHIJK
ABCXYZGHIJK
ABCDXYZHIJK
ABCDEXYZIJK

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.