Best way to do a case insensitive replace but match the case of the word to be replaced?

2024/10/10 4:23:06

So far I've come up with the method below but my question is is there a shorter method out there that has the same result?

My Code :

input_str       = "myStrIngFullOfStUfFiWannAReplaCE_StUfFs"
replace_str     = "stuff"
replacer_str    = "banana"print input_str
# prints: myStrIngFullOfStUfFiWannAReplaCE_StUfFsif replace_str.lower() in input_str.lower():            # Check if even in the stringbegin_index = input_str.lower().find( replace_str )end_index   = begin_index + len( replace_str )replace_section = input_str[ begin_index : end_index ]case_list = []for char in replace_section:                        # Get cases of characters in the section to be replacedcase_list.append( char.istitle() )while len( replacer_str ) > len(case_list):case_list += case_listsameCase_replacer_str   = ""                        # Set match the replacer string's case to the replacereplacer_str            = replacer_str.lower()for index in range( len(replacer_str) ):char = replacer_str[ index ]case = case_list[ index ]if case == True:char = char.title()sameCase_replacer_str += charinput_str = input_str.replace( replace_section , sameCase_replacer_str )print input_str
# prints: myStrIngFullOfBaNaNAiWannAReplaCE_BaNaNAs
Answer

I'd use something like this:

import redef replacement_func(match, repl_pattern):match_str = match.group(0)repl = ''.join([r_char if m_char.islower() else r_char.upper()for r_char, m_char in zip(repl_pattern, match_str)])repl += repl_pattern[len(match_str):]return replinput_str = "myStrIngFullOfStUfFiWannAReplaCE_StUfFs"
print re.sub('stuff',lambda m: replacement_func(m, 'banana'),input_str, flags=re.I)

Example output:

myStrIngFullOfBaNaNaiWannAReplaCE_BaNaNas

Notes:

  • This handles the case in which the different matches have different upper/lower case combinations.
  • It's assumed that the replacement pattern is in lower case (that's very easy to change, anyway).
  • If the replacement pattern is longer than the match, the same case as in the pattern is used.
https://en.xdnf.cn/q/69938.html

Related Q&A

Given a list of numbers, find all matrices such that each column and row sum up to 264

Lets say I have a list of 16 numbers. With these 16 numbers I can create different 4x4 matrices. Id like to find all 4x4 matrices where each element in the list is used once, and where the sum of each …

How can I access tablet pen data via Python?

I need to access a windows tablet pen data (such as the surface) via Python. I mainly need the position, pressure, and tilt values.I know how to access the Wacom pen data but the windows pen is differe…

Read Celery configuration from Python properties file

I have an application that needs to initialize Celery and other things (e.g. database). I would like to have a .ini file that would contain the applications configuration. This should be passed to th…

numpys tostring/fromstring --- what do I need to specify to restore the array

Given a raw binary representation of a numpy array, what is the complete set of metadata needed to unambiguously restore the array? For example, >>> np.fromstring( np.array([42]).tostring())…

How to limit width of column headers in Pandas

How can I limit the column width within Pandas when displaying dataframes, etc? I know about display.max_colwidth but it doesnt affect column names. Also, I do not want to break the names up, but rath…

Django + Auth0 JWT authentication refusing to decode

I am trying to implement Auth0 JWT-based authentication in my Django REST API using the django-rest-framework. I know that there is a JWT library available for the REST framework, and I have tried usin…

How to measure the angle between 2 lines in a same image using python opencv?

I have detected a lane boundary line which is not straight using hough transform and then extracted that line separately. Then blended with another image that has a straight line. Now I need to calcula…

How to modify variables in another python file?

windows 10 - python 3.5.2Hi, I have the two following python files, and I want to edit the second files variables using the code in the first python file.firstfile.pyfrom X.secondfile import *def edit(…

SciPy optimizer ignores one of the constraints

I am trying to solve an optimization problem where I need to create a portfolio that with a minimum tracking error from benchmark portfolio and its subject to some constraints:import scipy.optimize as …

How can one use HashiCorp Vault in Airflow?

I am starting to use Apache Airflow and I am wondering how to effectively make it use secrets and passwords stored in Vault. Unfortunately, search does not return meaningful answers beyond a yet-to-be-…