简体   繁体   中英

How to split a string on all occurences of a character but the last one in python?

I am trying to iterate through rows of a dataset and split a list of strings from one of its columns. The split is done on the character ":".

The string always end with a redundant ":", so the split returns an empty string at the last index.

I am currently iterating through my results, removing the last empty item from each result.

Is there an efficient way to split all but the last occurrence of the column without knowing how many occurrences of the split each string has?


Example string looks like

 [abc:def:ghi:...:xyz:]

And I split it using the code:

answers = [exSheet.cell_value(r,6).split(':') for r in range(1, exSheet.nrows)]

To return all split values, except for the last value, because it's empty in your case, you can return the split result list with index [0:-1]

You can find examples of list indices tricks here: Useful List tricks in Python by RatulSaha

For example, lets say your data is

a='1:2:3:4:'

You can split it like this

a.split(':')

to get this:

Out[3]: ['1', '2', '3', '4', '']

or you can split it like this

a.split(':')[0:-1]

to get your wanted result

Out[4]: ['1', '2', '3', '4']

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