Splitting a string variable into chunks 16 characters long
本问题已经有最佳答案,请猛点这里访问。
我是个有点像Python的笨蛋!我正在尝试将一个字符串(长度介于0到32个字符之间)拆分为两个16个字符的块,并将每个块另存为一个单独的变量,但我不知道如何进行。
这是我的意思的伪代码大纲:
1 2 3 4 | text ="The weather is nice today" split 'text' into two 16-character blocks, 'text1' and 'text2' print(text1) print(text2) |
将输出以下内容:
1 2 | The weather is n ice today |
号
我在一个2x16字符的液晶显示器上显示输入到Raspberry PI的文本,我需要将文本拆分为行以写入LCD-我将文本写入LCD,如下所示:
" text2)
这适用于任何
1 2 3 | 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 |
或者你也可以这样做
1 2 3 | text ="The weather is nice today" for i in range(0, len(text), 16): print (text[i:i+16]) |
。
1 2 3 4 5 6 | text ="The weather is nice today" text1, text2 = [text[i: i + 16] for i in range(0, len(text), 16)] print(text1) print(text2) |
。
它将打印:
1 2 | The weather is n ice today |
号
通过指定索引,可以将文本分割为两个字符串变量。[:16]基本上是0到15,[16:]16是字符串中的最后一个字符
1 2 | text1 = text[:16] text2 = text[16:] |
字符串就像一个列表。
您可以拆分它或在字符串中计算字符数。
例子:
1 2 3 4 5 6 7 | word = 'www.BellezaCulichi.com' total_characters = len(word) print(str(total_characters)) # it show 22, 22 characters has word |
。
您可以拆分字符串并获取前5个字符
1 2 3 4 5 6 7 8 9 10 | 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 |
可以将拆分结果存储在变量中:
1 | first_part = word[0:15] |
。
尝试如下操作:
1 2 3 4 5 | 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)) |
。
1 2 3 4 5 | text ="The weather is nice today" text1, text2 = text[:16], text[16:32] print(text1) print(text2) |
印刷品:
1 2 | The weather is n ice today |
号