本文介紹了將字符串拆分為 2 個(gè)字母的段的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我有一個(gè)字符串,我需要將它分成 2 個(gè)字母的部分.例如,'ABCDXY'
應(yīng)該變成 ['AB', 'CD', 'XY']
.奇數(shù)字符情況下的行為可能完全是任意的(我會(huì)提前檢查長度).
I have a string, which I need to split into 2-letter pieces. For example, 'ABCDXY'
should become ['AB', 'CD', 'XY']
. The behavior in the case of odd number of characters may be entirely arbitrary (I'll check the length in advance).
有沒有什么辦法可以避免丑陋的循環(huán)?
Is there any way to do this without an ugly loop?
推薦答案
>>> [s[i:i + 2] for i in range(0, len(s), 2)]
['AB', 'CD', 'XY']
這篇關(guān)于將字符串拆分為 2 個(gè)字母的段的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!