蟒蛇 |以不同方式拆分字符串的方法

| | | | |

示例:

輸入: Paras_Jain_Moengage_best
輸出: [`Paras`, ` Paras_Jain`, `Paras_Jain_Moengage`, `Paras_Jain_Moengage_best`]

輸入: chunky_2808_GFG_Codechef
輸出: [`chunky`, `chunky_2808 , `chunky_2808_GFG `, `chunky_2808_GFG_Codechef`]

這裡有一些方法。

方法一:使用迭代

< br>

# 以子串方式分割字符串的 Python 代碼


# 初始化輸入

Input = "Geeks_for_geeks_is_best "


# 除法——å 初始化

split_string = 輸入 。 split ( `_` )


# 初始化輸出列表

輸出 = []


# 迭代

for a in range ( len (split_string)):

temp = split_string [: a + 1 ]

temp = "_" 。 join (temp)

Output.append (temp)


# 打印輸出

print (輸出)

退出:

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

方法2:使用Itertools


# Python以子字符串方式拆分字符串的代碼


# Import

from itertools import 累積


# 初始化輸入

Input = "Geeks_for_geeks_is_best"


# 使用累積

輸出 = [ * 累加( Input 。 split ( `_` ), lambda temp1, temp2:

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


#打印輸出

print (輸出)

Exit:

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