Python | Maneras de dividir una cadena de diferentes maneras

| | | | |

Ejemplos:

Entrada: Paras_Jain_Moengage_best
Salida: [`Paras`, ` Paras_Jain`, `Paras_Jain_Moengage`, `Paras_Jain_Moengage_best`]

Entrada: chunky_2808_GFG_Codechef
Salida: [`chunky`, `chunky_2808 , `chunky_2808_GFG `, `chunky_2808_GFG_Codechef`]

Aquí hay algunas formas de hacerlo.

Método # 1: Usar iteración

< br>

# Código de Python para dividir una cadena en forma de subcadena


# Inicializar entrada

Input = "Geeks_for_geeks_is_best "


# Divide —å inicialización

split_string = Entrada . split ( `_` )


# Inicializar la lista de salida

Output = []


# Iteración

para a en rango ( len (cadena_dividida)):

temp = split_string [: a + 1 ]

temp = " _ " . unirse (temp)

Output.append (temp)


# printout

print (Salida)

Salir:

[ `Geeks`, `Geeks_for`, `Geeks_for_geeks`, `Geeks_for_geeks_is`, `Geeks_for_geeks_is_best`]

Método 2: Usar Itertools


# Python código para dividir la cadena en forma de subcadena


# Importar

de itertools importar acumular


# Inicializar entrada

Entrada = "Geeks_for_geeks_is_best"


# Uso para acumular

Salida = [ * acumular ( Entrada . split ( `_` ), lambda temp1, temp2:

`_` . join ([temp1, temp2])),]


# Impresión

imprimir (Salida)

Salir:

[`Geeks`, `Geeks_for`, `Geeks_for_geeks`, `Geeks_for_geeks_is`, `Geeks_for_geeks_is_best`]

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method