Python 将字符串变量拆分为16个字符长的块

Python 将字符串变量拆分为16个字符长的块,python,string,split,raspberry-pi,lcd,Python,String,Split,Raspberry Pi,Lcd,我有点像巨蟒迷!我试图将一个字符串(长度在0到32个字符之间)拆分为两个16个字符的块,并将每个块保存为一个单独的变量,但我无法确定如何进行 这是我的意思的伪代码概述: text = "The weather is nice today" split 'text' into two 16-character blocks, 'text1' and 'text2' print(text1) print(text2) 这将输出以下内容: The weather is n ice today

我有点像巨蟒迷!我试图将一个字符串(长度在0到32个字符之间)拆分为两个16个字符的块,并将每个块保存为一个单独的变量,但我无法确定如何进行

这是我的意思的伪代码概述:

text = "The weather is nice today"
split 'text' into two 16-character blocks, 'text1' and 'text2'
print(text1)
print(text2)
这将输出以下内容:

The weather is n
ice today       
我正在显示连接到raspberry pi的2x16字符LCD上输入的文本,我需要将文本拆分为几行以写入LCD-我正在将文本写入LCD,如下所示:
LCD.message(text1“\n”text2)
,因此块的长度必须精确为16个字符

text = "The weather is nice today"

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

The weather is n
ice today
印刷品:

The weather is n
ice today

通过指定索引,可以将文本分为两个字符串变量。[:16]基本上是0到15,[16:]是16到字符串中的最后一个字符

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

通过指定索引,可以将文本分为两个字符串变量。[:16]基本上是0到15,[16:]是16到字符串中的最后一个字符

text1 = text[:16]
text2 = text[16:]
它将打印:

The weather is n
ice today
它将打印:

The weather is n
ice today

试着这样做:

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))

试着这样做:

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))

字符串就像一个列表

您可以拆分它或计算字符串中的字符数

例如:

word = 'www.BellezaCulichi.com'


total_characters = len(word)

print(str(total_characters))
# it show 22, 22 characters has word
您可以拆分字符串并获得前5个字符

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
您可以将拆分结果存储在变量中:

first_part = word[0:15]

字符串就像一个列表

您可以拆分它或计算字符串中的字符数

例如:

word = 'www.BellezaCulichi.com'


total_characters = len(word)

print(str(total_characters))
# it show 22, 22 characters has word
您可以拆分字符串并获得前5个字符

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
您可以将拆分结果存储在变量中:

first_part = word[0:15]

这将适用于任何
文本

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
或者你也可以这样做

text = "The weather is nice today"
for i in range(0, len(text), 16):
    print (text[i:i+16])

这将适用于任何
文本

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
或者你也可以这样做

text = "The weather is nice today"
for i in range(0, len(text), 16):
    print (text[i:i+16])

如果
text
长度不完全为32个字符,您希望发生什么?如果
text
长度不完全为32个字符,您希望发生什么?这是迄今为止最好的方法,因为它使用列表理解。这是迄今为止最好的方法,因为它使用列表理解