Reputation: 89
I have a question on Python string operation:
Here's a string in which there are multiple .(dot),
like:
"a3a.b1b2b.cccc.ded.f.g"
The question is to find the content before the last .(dot), which is
"a3a.b1b2b.cccc.ded.f"
in this example (We call it as STRING_BEFORE_LAST_DOT)
and we need to replace STRING_BEFORE_LAST_DOT to be STRING_BEFORE_LAST_DOT + "_Approved".
So the result should be:
"a3a.b1b2b.cccc.ded.f_Approved.g"
.
And some more examples:
"a.b" -> "a_Approved.b"
"first.second.c" -> "first.second_Approved.c"
I can def a function to do so, I'm wondering if there's any advance way, like use .replace() to make it happen. Thanks.
Upvotes: 1
Views: 228
Reputation: 163362
You can use a pattern to match from the last dot until the end of the string .[^.]*$
Then replace with _Approved and add the full match after it using \g<0>
print(re.sub(r"\.[^.]*$", r"_Approved\g<0>", "a3a.b1b2b.cccc.ded.f.g"))
Output
a3a.b1b2b.cccc.ded.f_Approved.g
Upvotes: 0
Reputation: 1
Here is an alternative. You can access every dot's index with this:
import re
str = "a3a.b1b2b.cccc.ded.f"
# Finds every dot's starting index. (For ending of matched value d.end())
dots = [d.start(0) for d in re.finditer(r'\.+', str)]
# _Approved added
str = str[:dots[-1]] + "_Approved" + str[dots[-1]:]
Upvotes: 0
Reputation: 5935
An example of how to do it with a regexp:
import re
s = "a3a.b1b2b.cccc.ded.f.g"
no_ext = re.split(r'\.[^\.]*$', s)[0]
Upvotes: 0
Reputation: 21
# your String
string = 'a3a.b1b2b.cccc.ded.f.g'
# find the last dot character in your string
StringIndex = string.rfind('.')
# create a temporary list of your string and swap the last dot with your preferred string (_Approved.)
temp = list(string)
temp[StringIndex] = '_Approved.'
# replace
string = ''.join(temp)
# print
print('Old String: a3a.b1b2b.cccc.ded.f.g \nNew String: '+ string)
# OUTPUT
# Old String: a3a.b1b2b.cccc.ded.f.g
# New String: a3a.b1b2b.cccc.ded.f_Approved.g
Upvotes: 1
Reputation: 8302
Here is a solution you can try out,
def _replace(input_):
sub_ = input_[input_.rfind("."):]
return input_.replace(sub_, f"_Approved{sub_}")
print(_replace("a.b"))
print(_replace("first.second.c"))
a_Approved.b
first.second_Approved.c
Upvotes: 0
Reputation: 14523
You could use join
+ rsplit
with a limit of 1:
>>> "_Approved.".join("a.b".rsplit(".",1))
'a_Approved.b'
>>> "_Approved.".join("first.second.c".rsplit(".",1))
'first.second_Approved.c'
Upvotes: 2