How to split a string based on underscore but conditional

kulfi

I have a string below which altogether joined by underscores _ that i want to split in such a way to get my desired output.

Below is list string:

>>> a
'cDOT_stv3027_esx_vdi01_07-24-2021_02.00.00.0443'

>>> type(a)
<type 'str'>

Simple rsplit() operation by 2 which turns it into 3 different list values as shown below, like from the end its time , date and then one combine strings ie 'cDOT_stv3027_esx_vdi01' which i want to split into two parts like 'cDOT' & 'stv3027_esx_vdi01'.

>>> a.rsplit("_",2)
['cDOT_stv3027_esx_vdi01', '07-24-2021', '02.00.00.0443']

I am trying below on the first index but then i'll not retain rest of values.

>>> a.rsplit("_",2)[0].split("_",1)
['cDOT', 'stv3027_esx_vdi01']

My desired output should be like below:

['cDOT', 'stv3027_esx_vdi01', '07-24-2021', '02.00.00.0443']
Wiktor Stribiżew

You can use

a = 'cDOT_stv3027_esx_vdi01_07-24-2021_02.00.00.0443'
prefix, *mid, date, time = a.split('_')
print(prefix, '_'.join(mid), date, time)

See the online Python demo.

In this case, you can have as many underscore separated parts between the prefix and date as there are.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

how to split a string by last underscore

How to split a string based on a semicolon following a conditional digit

How can I split a sentence based on underscore in Java

How to split a string based on a char

How to split a string into 2 at the last occurrence of an underscore character

How to split a string by underscore and extract an element as a variable in bash?

How to split a string by underscore and extract an element as a variable in bash?

Conditional String Split based on another column str Python

c# split string by underscore

How to split string based on position in string

How to 'split' a pandas df column based on conditional and pivot the df

Conditional based regex split in python

How to split a long string based on delimiter in R

How to split a string based on punctuation marks and whitespace?

How to split a string based on a condition in scala?

How to split a string based of capital letters?

How to split string into two parts based on last "/"

Powershell - How to split a string based on characters?

Java - How to split a string which is column based?

How to split a integer string based on the character present in it

how to split String based on \r\n

How to split a string based on either a colon or a hyphen?

How to split a java string based on newline character

How to split a string based on space and a limit?

How to split a string in javascript based on this specific scenario

How to split String based on a Char, if it is in an ArrayList?

How to split a string based on ":" in MS-Excel?

How to split a string based on two regex formats?

How to split text string in R based on capitalization?