leanghy
leanghy

Reputation: 50

How to split string with multiple delimiters in Python?

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

Upvotes: 0

Views: 429

Answers (3)

Neeraj
Neeraj

Reputation: 997

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

Upvotes: 1

user14185615
user14185615

Reputation:

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

Upvotes: 1

Shashank Mistry
Shashank Mistry

Reputation: 78

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

Upvotes: 2

Related Questions