簡體   English   中英

用Python中另一個字符串的第n個字符創建一個字符串

[英]Create a string with every nth character of another string in Python

我想分割一個字符串,結果是一個僅由原始字符串的第n個字符組成的字符串。 我的第一種方法看起來像這樣(可行):

#Divide the cipher text in the estimated number of columns
for i in range(0,keyLengthEstimator):
    cipherColumns.append(cipherstring[i])

for i in range(keyLengthEstimator,len(cipherstring)):
    if i % keyLengthEstimator == 0:
        cipherColumns[0] += cipherstring[i]
    elif i % keyLengthEstimator == 1:
        cipherColumns[1] += cipherstring[i]
    elif i % keyLengthEstimator == 2:
        cipherColumns[2] += cipherstring[i]
    elif i % keyLengthEstimator == 3:
        cipherColumns[3] += cipherstring[i]
    elif i % keyLengthEstimator == 4:
        cipherColumns[4] += cipherstring[i]

我覺得有一種更有效的方法可以做到這一點。 在Matlab中會有reshape函數,Python中有類似的函數嗎?

為什么不簡單:

#Divide the cipher text in the estimated number of columns
for i in range(0,keyLengthEstimator):
    cipherColumns.append(cipherstring[i])

for i in range(keyLengthEstimator,len(cipherstring)):
    cipherColumns[i % keyLengthEstimator] += cipherstring[i]

您可以將字符串切片N次,為每個字符串指定N的步長:

>>> s = "Hello I am the input string"
>>> columns = 5
>>> seq = [s[i::columns] for i in range(columns)]
>>> print seq
['H  i n', 'eItnsg', 'l hpt', 'laeur', 'om ti']
>>> print "\n".join(seq)
H  i n
eItnsg
l hpt
laeur
om ti

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM