根据最后一次出现的分隔符将字符串拆分为2

时间:2021-07-31 21:38:33

I would like to know if there is any built in function in python to break the string in to 2 parts, based on the last occurrence of a separator.

我想知道在python中是否有任何内置函数将字符串分成两部分,基于最后一次出现的分隔符。

for eg: consider the string "a b c,d,e,f" , after the split over separator ",", i want the output as

例如:考虑字符串“a b c,d,e,f”,在拆分分隔符“,”之后,我希望输出为

"a b c,d,e" and "f".

“a b c,d,e”和“f”。

I know how to manipulate the string to get the desired output, but i want to know if there is any in built function in python.

我知道如何操作字符串来获得所需的输出,但我想知道python中是否有任何内置函数。

3 个解决方案

#1


95  

Use rpartition(s). It does exactly that.

使用rpartition(s)。它确实如此。

You can also use rsplit(s, 1).

你也可以使用rsplit(s,1)。

#2


61  

>>> "a b c,d,e,f".rsplit(',',1)
['a b c,d,e', 'f']

#3


40  

You can split a string by the last occurrence of a separator with rsplit:

您可以使用rsplit在分隔符的最后一次出现时拆分字符串:

Returns a list of the words in the string, separated by the delimiter string (starting from right).

返回字符串中单词的列表,由分隔符字符串(从右开始)分隔。

To split by the last comma:

要按最后一个逗号分割:

>>> "a b c,d,e,f".rsplit(',', 1)
['a b c,d,e', 'f']

#1


95  

Use rpartition(s). It does exactly that.

使用rpartition(s)。它确实如此。

You can also use rsplit(s, 1).

你也可以使用rsplit(s,1)。

#2


61  

>>> "a b c,d,e,f".rsplit(',',1)
['a b c,d,e', 'f']

#3


40  

You can split a string by the last occurrence of a separator with rsplit:

您可以使用rsplit在分隔符的最后一次出现时拆分字符串:

Returns a list of the words in the string, separated by the delimiter string (starting from right).

返回字符串中单词的列表,由分隔符字符串(从右开始)分隔。

To split by the last comma:

要按最后一个逗号分割:

>>> "a b c,d,e,f".rsplit(',', 1)
['a b c,d,e', 'f']