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

时间:2018-07-31 15:39:16

标签: 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       

我正在显示在与树莓派相连的2x16字符LCD上输入的文本,我需要将文本分成几行以写入LCD-我正在将文本写入LCD像这样:{{1 }},因此块的长度必须恰好为16个字符。

6 个答案:

答案 0 :(得分:1)

可以通过指定索引将文本切成两个字符串变量。 [:16]基本上是0到15,[16:]则是字符串末尾的16个字符

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

答案 1 :(得分: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)

它将打印:

The weather is n
ice today

答案 2 :(得分:1)

这将适用于任何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

或者您也可以这样做

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

答案 3 :(得分:0)

text = "The weather is nice today"

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

打印:

The weather is n
ice today

答案 4 :(得分:0)

尝试这样的事情:

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

答案 5 :(得分:0)

字符串就像一个列表。

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

示例:

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]