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 OverflowI'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'
This seems to be fastest:
s = "this is my/string"
mytext = s[:s.rindex('/')] + '/text'
What I've tested:
>>> s = "this is my/string"
>>> pattern = re.compile('/.*$')
>>> %timeit pattern.sub('/text', s)
1000000 loops, best of 3: 730 ns per loop
>>> %timeit s[:s.rindex('/')] + '/text'
1000000 loops, best of 3: 284 ns per loop
>>> %timeit s.rsplit('/', 1)[0] + '/text'
1000000 loops, best of 3: 321 ns per loop
Hey ! I was wondering if there is any replace function to replace a string from a starting position in the text string in Python?
How to replace a character at beginning and end of a string in python - Stack Overflow
python - Replace pairs of characters at start of string with a single character - Stack Overflow
regex - replace character if it appears only at beginning of string using re.sub in Python - Stack Overflow
I am not sure what you want to achive, but it seems you just want to replace a '1' for an 'I' just once, so try this:
string = "11234"
string.replace('1', 'I', 1)
str.replace takes 3 parameters old, new, and count (which is optional). count indicates the number of times you want to replace the old substring with the new substring.
In Python, strings are immutable meaning you cannot assign to indices or modify a character at a specific index. Use str.replace() instead. Here's the function header
str.replace(old, new[, count])
This built in function returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
If you don't want to use str.replace(), you can manually do it by taking advantage of splicing
def manual_replace(s, char, index):
return s[:index] + char + s[index +1:]
string = '11234'
print(manual_replace(string, 'I', 0))
Output
I1234
i want to apply this to a dataframe column with different text content across the column and i want to replace the text from a starting position in the string. thanks you guy would help me a lot
You could use a negative look behind and specify only a single replace to occur:
>>> import re
>>> s = 'paper'
>>> re.sub('(?<!^)p', 'k', s, 1)
'paker'
But then you could do that without a regex as such:
s[0] + s[1:].replace('p', 'k', 1)
Try this, using capturing groups and back references to capture all that's before the second p and all that's after the second p:
re.sub(r'(.+)p(.+)', r'\1k\2', string)
=> 'paker'
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.
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.