2016-05-24 14 views
1

文字列を分割して、元の文字列のn番目ごとの文字列のみを含む文字列を分割したいとします。私の最初のアプローチは次のようになります: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には、変形機能がありますが、Pythonにも同様の機能がありますか?あなたが各1についてNのステップを指定して、文字列の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)): 
    cipherColumns[i % keyLengthEstimator] += cipherstring[i] 
+1

あなたはいくつかの例の入力と出力を提供してもらえますか? – mattsap

答えて

2

:なぜ単に

+0

まさに私が探していたもの、ありがとう! – smonsays

2

>>> 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 
+0

ありがとう!それははるかにエレガントです! – smonsays

関連する問題