1

I would like to split a string with the result being a string consisting only of every nth character of the original string. My first approach looks like this (and works):

#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]

I have the feeling, that there is a more efficient way to do it. In Matlab there would be the reshape function, is there a similar function in Python?

1
  • 1
    Could you provide some example inputs and outputs? Commented May 24, 2016 at 19:01

2 Answers 2

2

You could slice the string N times, specifying a step of N for each one:

>>> 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
Sign up to request clarification or add additional context in comments.

Comments

2

Why not simply:

#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 Comment

Thank you! That's much more elegant!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.