0

Let's say I have a string "abc_123_def" and I want to "remove" "abc_" and "_def" and be left with "123".

I currently have two replace statements:

s = "abc_123_def"
s.replace("abc_",'')
s.replace("_def",'')

Is there a better, one-liner way to do so?

1
  • 1
    I want to remove those specific sequences. Commented Jul 22, 2019 at 16:54

2 Answers 2

1
s = "abc_123_def"
s = s.replace("abc_",'').replace("_def",'')
Sign up to request clarification or add additional context in comments.

3 Comments

I didn't realize python let you chain methods like that!
Any decent language will let you chain calls like that so long as the call returns a value.
Yes because s.replace("abc_",'') returns a string, which can then be put into another function call.
0

You can use regex like below, to exactly identify the values between underscores.

>>> import re
>>> s = 'abc_123_def'
>>> re.findall('_(.*?)_', s)[0]
'123'
>>>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.