Search code examples
pythonstringsplitraspberry-pilcd

Splitting a string variable into chunks 16 characters long


I'm a bit of a python noob! I'm trying to split a string (of length between 0 and 32 characters) into two blocks of 16 characters and save each chunk as a separate variable, but I can't work out how.

This is a pseudocode outline of what I mean:

text = "The weather is nice today"
split 'text' into two 16-character blocks, 'text1' and 'text2'
print(text1)
print(text2)

Which would output the following:

The weather is n
ice today       

I'm displaying the text entered on a 2x16 character LCD connected to a raspberry pi and I need to split the text into lines to write to the LCD - I'm writing the text to the LCD like this: lcd.message(text1 "\n" text2)so the chunks have to be 16 characters long exactly.


Solution

  • The text can be sliced into two string variables by specifying the indices. [:16] is basically 0 to 15 and [16:] is 16 to last character in string

    text1 = text[:16]
    text2 = text[16:]