简体   繁体   English

如何在 Python 中使用多个分隔符拆分字符串?

[英]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但是我得到的结果是com-bonding_err_bond0-if_eth2-d但我的目的是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.如果您被允许使用除正则表达式之外的解决方案,您可以将解决方案分成更小的部分以更好地理解并了解join (如果您不知道)。 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 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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