![](/img/trans.png)
[英]How to split a string into characters and assign each character to a separate variable
[英]How to split a string into list of characters and then concatenate by each character
是否可以每第n個字符分割一個Python字符串,然后連接后續字符?
例如,假設我有一個包含'Coffee'
的字符串。
我如何拆分並獲得這些變化:
C
Co
Cof
Coff
Coffe
Coffee
或者,在Python 3.2+中, itertools.accumulate()
。
>>> list(itertools.accumulate("Coffee"))
['C', 'Co', 'Cof', 'Coff', 'Coffe', 'Coffee']
值得注意的是,這可能不是一種特別有效的方法,因為它(內部)將使用很多字符串連接,我只是出於興趣而提供,而不是最好的方法。
您可以使用for循環:
>>> s = 'Coffee'
>>> for i in range(len(s)):
... print s[:i+1]
C
Co
Cof
Coff
Coffe
Coffee
或列表理解:
>>> [s[:i+1] for i in range(len(s))]
['C', 'Co', 'Cof', 'Coff', 'Coffe', 'Coffee']
既然您已經有了一些可行的解決方案,那么沒人會因為把腦筋急轉彎扔在臉上而把我釘在十字架上。 玩這個:
map(lambda x:x[::-1],re.findall(r"(?=(.+))","Coffee"[::-1]))[::-1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.