Python | Modi per dividere una stringa in diversi modi

| | | | |

Esempi:

Input: Paras_Jain_Moengage_best
Output: [`Paras`, ` Paras_Jain`, `Paras_Jain_Moengage`, `Paras_Jain_Moengage_best`]

Input: chunky_2808_GFG_Codechef
Output: [`chunky`, `chunky_2808 , `chunky_2808_GFG `, `chunky_2808_GFG_Codechef`]

Ecco alcuni modi per farlo.

Metodo n. 1: utilizzo dell`iterazione

< br>

# Codice Python per dividere una stringa in una sottostringa


# Inizializza input

Input = "Geeks_for_geeks_is_best "


# Divide —å inizializzazione

split_string = Input . split ( `_` )


# Inizializza l`elenco di output

Output = []


# Iterazione

per a in intervallo ( len (split_string)):

temp = split_string [: a + 1 ]

temp = " _ " . join (temp)

Output.append (temp)


# printout

print (Output)

Esci:

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

Metodo 2: utilizzo di Itertools


# Python codice per dividere la stringa in una sottostringa


# Importa

from itertools import accumula


# Inizializza input

Input = "Geeks_for_geeks_is_best"


# Utilizzo per accumulare

Output = [ * accumulare ( Input . split ( `_` ), lambda temp1, temp2:

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


# Stampa

print (Output)

Esci:

[`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