0

My First String

xxx.xxx.com-bonding_err_bond0-if_eth2-d.rrd.csv

But I want to result like this below

bonding_err_bond0-if_eth2

I try some code but seems not work correctly

csv = "xxx.xxx.com-bonding_err_bond0-if_eth2-d.rrd.csv"

x = csv.rsplit('.', 4)[2]

print(x)

But Result that I get is com-bonding_err_bond0-if_eth2-d But my purpose is bonding_err_bond0-if_eth2

2
  • you could split the output again on - and join the required slice: x = '-'.join(x.split('-')[1:-1]) Commented Apr 9, 2021 at 4:27
  • Are you needing to search for similar strings which may have different interface id's? Will the pattern change? Commented Apr 9, 2021 at 4:29

3 Answers 3

2

If you are allowed to use the solution apart from regex, You can break the solution into a smaller part to understand better and learn about join if you are not aware of it. It will come in handy.

solution= '-'.join(csv.split('.', 4)[2].split('-')[1:3])

Thanks, Shashank

Sign up to request clarification or add additional context in comments.

Comments

1

Probably you got the answer, but if you want a generic method for any string data you can do this:

In this way you wont be restricted to one string and you can loop the data as well.

csv = "xxx.xxx.com-bonding_err_bond0-if_eth2-d.rrd.csv"

first_index = csv.find("-")
second_index = csv.find("-d")

result = csv[first_index+1:second_index]
print(result)
# OUTPUT:
# bonding_err_bond0-if_eth2

Comments

1

You can just separate the string with -, remove the beginning and end, and then join them back into a string.

csv = "xxx.xxx.com-bonding_err_bond0-if_eth2-d.rrd.csv"

x = '-'.join(csv.split('-')[1:-1])

Output

>>> csv
>>> bonding_err_bond0-if_eth2

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.