I'm not sure what you mean by optimized but i'd do:

>>> import re
>>> mytext = "this is my/string"
>>> re.sub('/.*','/text',mytext)
'this is my/text'
Answer from Chris Seymour on Stack Overflow
๐ŸŒ
ActiveState
code.activestate.com โ€บ recipes โ€บ 577252-lreplace-and-rreplace-replace-the-beginning-and-en
lreplace() and rreplace(): Replace the beginning and ends of a strings ยซ Python recipes ยซ ActiveState Code
June 4, 2010 - It would also be nicer to type this: ... def rreplace(pattern, sub, string): return string[-len(pat):] + sub if string.endswith(pat) else string ยท Dougal Sutherland 13 years, 10 months ago # | flag ... Mmh, I think the name is misleading. str.replace(what, replacement, count) takes three ...
Discussions

Hey ! I was wondering if there is any replace function to replace a string from a starting position in the text string in Python?
You can just do something like s[:i] + 'new text' or f'{s[:i]}new next', assuming I correctly understand what you mean by "replace the text." You can apply a function to a pandas.Series via the .apply method, so you'd do something like new_series = dataframe[column_name].apply(lambda s: ...) More on reddit.com
๐ŸŒ r/learnpython
2
1
September 13, 2022
How to replace a character at beginning and end of a string in python - Stack Overflow
I would like to replace ' at the beginning and end of the strings only and not in middle of strings. I am trying to make use of replace function of python to perform this task More on stackoverflow.com
๐ŸŒ stackoverflow.com
August 13, 2020
python - Replace pairs of characters at start of string with a single character - Stack Overflow
I only want this done at the start of the sting. Some examples (I want to replace "--" with "-"): "--foo" -> "-foo" "-----foo" -> "---foo" "foo--bar" -> "foo--bar" I can't simply use s. More on stackoverflow.com
๐ŸŒ stackoverflow.com
regex - replace character if it appears only at beginning of string using re.sub in Python - Stack Overflow
I've just been messing around trying to get this to work for the first letter of any word - without having the specify it: ... It needs a variable length lookbehind which is not supported by Python, so to get past this I reverse the string, use a variable length lookahead and then reverse the ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 21, 2013
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_string_replace.asp
Python String replace() Method
Remove List Duplicates Reverse ... Study Plan Python Interview Q&A Python Training ... The replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, ...
๐ŸŒ
Quora
quora.com โ€บ How-do-you-replace-the-first-two-characters-of-a-string-in-Python
How to replace the first two characters of a string in Python - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ python-replace-first-character-in-string
Replace First or First N characters in a String in Python | bobbyhadz
We used string slicing to replace the first or the first N characters of a string. The slice my_str[1:] starts at the character at index 1 and goes to the end of the string. ... The syntax for string slicing is my_str[start:stop:step]. The start index is inclusive, whereas the stop index is exclusive (up to, but not including). Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.
Find elsewhere
๐ŸŒ
Linux Hint
linuxhint.com โ€บ python_string_replacement
Python String Replacement using Pattern โ€“ Linux Hint
Create a python file with the following script to search and replace the part of the text in the place where the pattern matches. Here, a list of email addresses is assigned as text into the variable named emails. โ€˜@[a-z]โ€™ is used pattern for searching. It will search any sub-string starts with ...
๐ŸŒ
EyeHunts
tutorial.eyehunts.com โ€บ home โ€บ python replace the first character in string | example code
Python replace the first character in string | Example code
June 8, 2023 - def replace_first_character(string, new_character): if len(string) > 0: new_string = new_character + string[1:] return new_string else: return string # Example usage original_string = "hello world" new_string = replace_first_character(original_string, "H") print(new_string) # Output: "Hello world" Do comment if you have any doubts or suggestions on this Python string topic.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 63385032 โ€บ how-to-replace-a-character-at-beginning-and-end-of-a-string-in-python
How to replace a character at beginning and end of a string in python - Stack Overflow
August 13, 2020 - How about iterating over the string's characters and checking the surrounding characters for isalpha(): out = [] for ix, char in enumerate(path): # first make sure we have a surrounding character on each side if ix > 0 and ix < len(path): # now check for a quote and make sure that one of the surrounding characters are not letters if char == "'" and not (path[ix-1].isalpha() and path[ix+1].isalpha()): # if we find that case, replace the single quote char = '"' # add the character to the out list out.append(char) # join all the characters back together output = ''.join(out) print(output)
๐ŸŒ
Real Python
realpython.com โ€บ replace-string-python
How to Replace a String in Python โ€“ Real Python
October 22, 2025 - You can use the .replace() method for straightforward replacements, while re.sub() allows for more advanced pattern matching and replacement. Both of these tools help you clean and sanitize text data.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 31419979 โ€บ replace-pairs-of-characters-at-start-of-string-with-a-single-character
python - Replace pairs of characters at start of string with a single character - Stack Overflow
I also tried a regex, but I can't get it to work specifically with replacing pairs. I get as far as trying to replace r"^(?:(-){2})+" with r"\1", but that tries to replace the full block of dashes at the start, and I can't figure how to get it to replace only pairs within that block.
๐ŸŒ
Medium
parvez1487.medium.com โ€บ find-and-replace-first-occurrence-of-a-string-in-python-pythonpip-com-432fafdd21aa
Find and Replace First Occurrence of a String in Python โ€” pythonpip.com | by Parvez Alam | Medium
January 7, 2024 - PHP is a powerful language!.python ... love python. ** Process exited - Return Code: 0 ** Press Enter to exit terminal ยท The find() method is to locate the position of the first occurrence of the word, and then perform the replacement using slicing and concatenation. ... str: The string in which you want to search for the substring. substring: The substring you want to find in the string. start (optional): ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-string-replace
Python String replace() Method - GeeksforGeeks
October 28, 2024 - Explanation: Here, "Hello" is replaced by "Hi" throughout the string, resulting in "Hi World! Hi Python!". Note: Since replace() creates a new string, the original string remains unchanged. ... count (optional): Specifies the maximum number of replacements to perform.
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ string โ€บ replace
Python String replace()
If the old substring is not found, it returns a copy of the original string. ... # replacing 'cold' with 'hurt' print(song.replace('cold', 'hurt')) song = 'Let it be, let it be, let it be, let it be'
๐ŸŒ
Jobtensor
jobtensor.com โ€บ Tutorial โ€บ Python โ€บ en โ€บ String-Methods-replace
Python String replace(), Definition, Syntax, Parameters, Examples | jobtensor
startswith() strip() swapcase() title() translate() upper() zfill() The replace() method replaces a specified phrase with another specified phrase. Note that all occurrences of the specified phrase will be replaced, if nothing is specified. string.replace(oldvalue, newvalue, count) testStr ...
Top answer
1 of 2
8

replace.py

import re

input = [
    "Independence Day (Observed)",
    "Christmas Eve, Christmas Day (Observed)",
    "New Year's Eve, New Year's Day (Observed)",
    "Martin Luther King, Jr. Day"
]

for holiday in input:
    print re.sub('^(.*?, )?(.*?)( \(Observed\))$', '\\2', holiday)

Output

> python replace.py 
Independence Day
Christmas Day
New Year's Day
Martin Luther King, Jr. Day

Explanation

  • ^: Match at start of string.
  • (.*?, )?: Match anything followed by a command and a space. Make it a lazy match, so it doesn't consume the portion of the string we want to keep. The last ? makes the whole thing optional, because some of the sample input doesn't have a comma at all.
  • (.*?): Grab the part we want for later use in a capturing group. This part is also a lazy match because...
  • ( \(Observed\)): Some strings might have " (Observed)" on the end, so we declare that in a separate group here. The lazy match in the prior piece won't consume this.
  • $: Match at end of string.
2 of 2
1

I suggest

r'^(?:.*,\s*)?\b([^,]+)\s+\(Observed\).*'

Replace with r'\1' backreference.

See the regex demo.

Pattern details:

  • ^ - start of string
  • (?:.*,\s*)? - an optional sequence of:
    • .*, - any 0+ chars other than line break chars as many as possible, up to the last occurrence of , on the line and then the ,
    • \s* - 0 or more whitespaces
  • \b - a word boundary
  • ([^,]+) - 1 or more chars other than ,
  • \s+ - 1 or more whitespaces
  • \(Observed\) - a literal substring (Observed)
  • .* - any 0+ chars other than line break chars as many as possible up to the line end.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-string-replace-function-in-python-for-substring-substitution
Python String.Replace() โ€“ Function in Python for Substring Substitution
January 24, 2022 - Let's get started! When using the .replace() Python method, you are able to replace every instance of one specific character with a new one. You can even replace a whole string of text with a new line of text that you specify.