Python replaceable string replacement

I need to replace the string in a sensitive way. for example

  abc -> def
 Abc -> Def
 aBc -> dEf
 abC -> deF

What can I do using Python?

+6
python string replace
source share
8 answers
from string import maketrans "Abc".translate(maketrans("abcABC", "defDEF")) 
+7
source share

The method using regular expressions is used here. The key point is that when it finds a match, it first modifies the replacement string to match the wrapper of the matched string. This works because re.sub can accept a function instead of a replacement instead of a string.

 import re def case_sensitive_replace(s, before, after): regex = re.compile(re.escape(before), re.I) return regex.sub(lambda x: ''.join(d.upper() if c.isupper() else d.lower() for c,d in zip(x.group(), after)), s) test = ''' abc -> def Abc -> Def aBc -> dEf abC -> deF ''' result = case_sensitive_replace(a, 'abc', 'def') print(result) 

Result:

  def -> def
 Def -> Def
 dEf -> dEf
 deF -> deF
+5
source share

Turning around Mark Byers answer, Here is a solution that works to replace text of any length.
The trick is to send the re.sub () function.

 import re def case_sensitive_replace(string, old, new): """ replace occurrences of old with new, within string replacements will match the case of the text it replaces """ def repl(match): current = match.group() result = '' all_upper=True for i,c in enumerate(current): if i >= len(new): break if c.isupper(): result += new[i].upper() else: result += new[i].lower() all_upper=False #append any remaining characters from new if all_upper: result += new[i+1:].upper() else: result += new[i+1:].lower() return result regex = re.compile(re.escape(old), re.I) return regex.sub(repl, string) print case_sensitive_replace("abc Abc aBc abC ABC",'abc','de') print case_sensitive_replace("abc Abc aBc abC ABC",'abc','def') print case_sensitive_replace("abc Abc aBc abC ABC",'abc','defg') 

Result:

 de De dE de DE def Def dEf deF DEF defg Defg dEfg deFg DEFG 
+2
source share

For a long time, I thought I would post a proposal here, as some of them seem rather confusing.

 print map(lambda a, b: b.lower() if a.islower() else b.upper(), "aBc", "def") 

It assumes that both lines are the same length, however you can easily replace the lambda with the proper function and check for None on the first input.

+1
source share

Perhaps the re module is what you are looking for. In particular, the re.sub function can be used to easily find / replace strings.

0
source share

Not the most efficient way, and it is very rude, but probably something like this might work:

 def case_insensitive_replace(string, old, new): upper_indices = [idx for idx, char in enumerate(string) if char.isupper()] replaced = list(string.lower().replace(old.lower(), new.lower())) for idx in upper_indices: replaced[idx] = replaced[idx].upper() return "".join(replaced) 
0
source share

I understand that you want to change the second case of the line to fit the first line. I'm right? So my solution is as follows. Line s2 changes its case according to the corresponding line s1. The result is stored in s3. One of the assumptions here is that the two lines are the same length.

 s1 = "AaBb" s2 = "cdef" s3 = "" index = 0 length = len(s1) while(True): if s1[index].isupper(): temp = s2[index].upper() else: temp = s2[index].lower() s3 = s3 + temp index +=1 if index == length: break print s3 
0
source share

This will work, although you probably want to add some checks that the string lengths are the same:

 string1 = "AbcDEFghiJKLmnO" string2 = "some other text" string2 = "".join((string2[i].upper() if string1[i].isupper() else string2[i].lower() for i in range(len(string1)))) 
0
source share

All Articles