Manipulate User Input For A List
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
Solution 1:
You can use the textwrap
module for splitting your string into even sized chunks:
Using your sample of input ABABABAB
and 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.
Solution 2:
Using list comprehension with range
:
>>> user_input = 'ABABABABA'# user_input = raw_input("Enter message: ")>>> [user_input[i:i+2] for i inrange(0, len(user_input), 2)]
['AB', 'AB', 'AB', 'AB', 'A']
Post a Comment for "Manipulate User Input For A List"