根据最后出现的分隔符将字符串分成2个

问题:根据最后出现的分隔符将字符串分成2个

我想知道在python中是否有任何内置函数根据最后一次出现的分隔符将字符串分为2部分。

例如:考虑字符串“ abc,d,e,f”,在分隔符“,”分割后,我希望输出为

“ abc,d,e”和“ f”。

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

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.

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” and “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.


回答 0

使用rpartition(s)。它确实做到了。

您也可以使用rsplit(s, 1)

Use rpartition(s). It does exactly that.

You can also use rsplit(s, 1).


回答 1

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

回答 2

您可以使用最后一个分隔符来分割字符串rsplit

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

要以最后一个逗号分隔:

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

You can split a string by the last occurrence of a separator with 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']