Python Cutting a string to multiple variables

510 Views Asked by At

Im looking for a way to "cut" a string that comes from an html input into 4 variables, depending on the length of the original string. I need to do this because i want to show the string on the RaspberryPi LCD-Display. Because the LCD can only show 20 Letters per row, i thought about putting the rest of the string into another variable.

Right now my Pythoncode looks like this.

def text1(text):
    global TextA
    TextA = text
    TextA = urllib.request.unquote(TextA)
    subprocess.Popen(["espeak", "-vde",  TextA])
    subprocess.Popen(["python2", "/home/pibot/display.py", TextA])

The Part with espeak works perfect. The display output only works if the string contains less than 20 letters.

So basically i just want to split TextA into TextA1 TextA2 TextA3 and TextA4.

I thought about doing it with

if len(TextA) > 20

but i dont really know how to get further with this.

Thank you very much in advance.

2

There are 2 best solutions below

0
Jieter On BEST ANSWER

You can slice strings like this:

>>> 'very long string, much longer than 20 characters'[0:20]
'very long string, mu'

you don't need to check if the string is longer than 20 characters, you can just always add the slicing to your subprocess statement: TextA[0:20] will not touch the string if it's shorter than 20 characters.

0
DomTomCat On

If you don't need proper word wrapping, try a comprehension like this:

from math import ceil
str = 'very long string, much longer than maxLength characters.'\
      'very long string, much longer than maxLength characters'

maxLength = 20
numStringsOut = int(ceil(len(str)/float(maxLength)))

subStringList = [str[p * maxLength: p * maxLength + maxLength]
                 for p in range(numStringsOut)]
print(subStringList)

output:

['very long string, mu', 'ch longer than maxLe', 'ngth characters.very', ' long string, much l', 'onger than maxLength', ' characters']