0

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.

martineau
  • 119,623
  • 25
  • 170
  • 301

6 Answers6

1

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:]
Rik
  • 467
  • 4
  • 14
1
text = "The weather is nice today"

text1, text2 = [text[i: i + 16] for i in range(0, len(text), 16)]

print(text1)
print(text2)

It will print:

The weather is n
ice today
Waleed Iqbal
  • 106
  • 6
1

This would apply to any text

text = "The weather is nice today"
splitted = [text[i:i+16] for i  in range(0, len(text), 16)]
print (splitted) # Will print all splitted elements together

OR you can also do it like

text = "The weather is nice today"
for i in range(0, len(text), 16):
    print (text[i:i+16])
Sheldore
  • 37,862
  • 7
  • 57
  • 71
0
text = "The weather is nice today"

text1, text2 = text[:16], text[16:32]
print(text1)
print(text2)

Prints:

The weather is n
ice today
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

Try something like this:

s = "this is a simple string that is long"
size = 8
for sl in range(0, int(len(s)/size)):
   out = s[sl:sl + size]
   print(out, len(out))
tykom
  • 659
  • 5
  • 8
0

A string is like a list.

You can split it or count your characters in the string.

Example:

word = 'www.BellezaCulichi.com'


total_characters = len(word)

print(str(total_characters))
# it show 22, 22 characters has word

You can split the string and get the 5 first characters

print(word[0:5])
# it shows:  www.B
# the first 5 characters in the string



print(word[0:15])
# split the string and get the 15 first characters
# it shows:  www.BellezaCuli
# the first 5 characters in the string

You can store the result of the split in a variable:

first_part = word[0:15]