简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM