0

I am putting the user input into a list, but I was wondering how to change the format for how the input is stored in the list, for example:

Code

lst = list(raw_input("Enter message: "))

User Input

ABABABAB

Output

['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B']

Desired Output

['AB', 'AB', 'AB', 'AB'] 
user1902535
  • 155
  • 1
  • 3
  • 10

2 Answers2

2

You can use the textwrap module for splitting your string into even sized chunks:

Using your sample of input ABABABABand chunking into groups of 2:

>>> import textwrap
>>> lst = textwrap.wrap(raw_input("Enter message: "), 2)
Enter message: ABABABAB
>>> lst
['AB', 'AB', 'AB', 'AB']

Using the sample I suggested with input ABCABCABC and chunking into groups of 2:

>>> lst = textwrap.wrap(raw_input("Enter message: "), 2)
Enter message: ABCABCABC
>>> lst
['AB', 'CA', 'BC', 'AB', 'C']

Notice how the extra letter is all on it's own.

Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
1

Using list comprehension with range:

>>> user_input = 'ABABABABA' # user_input = raw_input("Enter message: ")
>>> [user_input[i:i+2] for i in range(0, len(user_input), 2)]
['AB', 'AB', 'AB', 'AB', 'A']
falsetru
  • 357,413
  • 63
  • 732
  • 636