2

I'm trying to replace a character within a string with an equivalent character in another string.

String after changes made:

#C/084&"
#3*#%#C

Original String:

#+/084&"
#3*#%#+

How can I replace all 'C's back to '+'?

2
  • Have you tried str.replace? Commented Mar 2, 2014 at 12:37
  • 4
    what makes characters "equivalent"? Commented Mar 2, 2014 at 12:39

4 Answers 4

2

Im not sure what you mean by "equivalent character", but if you mean replace all occurrences of a specific character anywhere in the string you can use string.replace('C','+').

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

2 Comments

I should have explained my question better, but what I mean is that I want to be able to find where all the C are in the string and replace it with another character in another string that is in the same position as it, without having to actually mention '+' in my code.
ok, than that would be something like: string.replace('C',another_string[some_index])
2

Use original_str.replace('C', '+')

Example:

>>> 'C++'.replace('C', '+')
'+++'
>>> 

UPDATE:

first = list('C/084&"')
second = '3*#%#C'

for i, x in enumerate(first):
     first[i] = first[i] if x!='C' else second[i]

first = ''.join(first)

After it first is 3/084&"

Comments

0

You can also re module for eg.

import re

string1 = '#+/084&"'
string2 = re.sub("+", "C", string1)
>>>string2
'#C/084&"'

Comments

0

You can easily do this with string.replace() function:

  string1 = "#3*#%#C"
  string2 = string1.replace("C","+")
  print(string2)

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.