The problem (try printing split) is that all elements in split are not necessarily rows long:
Type a string to encrypt: hello world
How many table columns would you like: 3
['hel', 'lo ', 'wor', 'ld']
You have to decide what you want to do. Maybe append spaces to the end of the last string if it's not long enough.
You might also want to have a look at enumerate. Happy hacking.
Update: Let's say you choose to use 2 columns, and a string length that is divisible by two:
Type a string to encrypt: helo
How many table columns would you like: 2
['he', 'lo']
['h', 'l', 'e', 'o']
Seems to work. Oh, I had to change your code a little because input doesn't do what you think:
def encrypt():
before = raw_input("Type a string to encrypt: ")
columns = int(raw_input("How many table columns would you like: "))
split = [before[i:i+columns] for i in range(0, len(before), columns)]
rows = len(split)
after = []
for i in range(0, columns):
for j in range(0,rows):
after.append(split[j][i])
print(after)
Update 2: If you want to pad the input using spaces, just add this line:
before += " " * (columns - len(before) % columns)
You'll end up with this code:
def encrypt():
before = raw_input("Type a string to encrypt: ")
columns = int(raw_input("How many table columns would you like: "))
before += " " * (columns - len(before) % columns)
split = [before[i:i+columns] for i in range(0, len(before), columns)]
rows = len(split)
after = []
for i in range(0, columns):
for j in range(0,rows):
after.append(split[j][i])
print ''.join(after)
Example output:
Type a string to encrypt: hello world
How many table columns would you like: 4
hore llwdlo
range(n)is the same asrange(0, n). the 0 is implicitiyou iterate over the columns and withjover each substring. So you should use them for that.