简体   繁体   English

每隔 n 个字符向后迭代拆分一个 Python 字符串

[英]Splitting a Python string every nth character iterating backwards

I'm working on a program that converts numbers to binary and vice versa.我正在开发一个将数字转换为二进制的程序,反之亦然。 When the user enters a binary string such as 1011110110 it's converted to decimal and printed.当用户输入诸如1011110110之类的二进制字符串时,它会被转换为十进制并打印出来。 I also want to print out the users inputted string like 10 1111 0110 .我还想打印出用户输入的字符串,例如10 1111 0110

I have tried我努力了

print("Binary \t=\t " + ' '.join(binaryString[i:i+4] for i in range(0, len(binaryString), 4)))

Which will print out as 1011 1101 10 .这将打印为1011 1101 10 I'm wanting the spaces to start at the end of the string working forward like 10 1111 0110 .我希望空格从字符串的末尾开始,如10 1111 0110

You can use the module % operator to know how many "overflow" numbers you have, then partition the remainder every 4th:您可以使用模块%运算符来了解您有多少“溢出”数字,然后每 4 次对余数进行分区:

def  neat_print(s):
    ls = len(s)
    start = ls % 4
    rv, s = s[:start], s[start:]
    return ' '.join([rv] + [s[i:i+4] for i in range(0,ls-start,4)]).strip()

for k in ["1010101010"[:end] for end in range(2,10)]:
    print(k, "->", neat_print(k))

Output: Output:

10 -> 10
101 -> 101
1010 -> 1010
10101 -> 1 0101
101010 -> 10 1010
1010101 -> 101 0101
10101010 -> 1010 1010
101010101 -> 1 0101 0101

You could use a recursive approach:您可以使用递归方法:

def rGroup(S,size=4,sep=" "):
    return S if len(S)<=size else rGroup(S[:-size],size,sep) + sep + S[-size:]

output: output:

rGroup('1010101010') # '10 1010 1010'

rGroup('12345678',3,',') # '12,345,678'

binaryString = "1011110110"    
print("Binary \t=\t " + rGroup(binaryString)) # Binary  =    10 1111 0110

Just add [::-1] in two places in your code:只需在代码中的两个位置添加[::-1]

' '.join(binaryString[::-1][i:i+4] for i in range(0, len(binaryString), 4))[::-1]

ps [::-1] reverse the string, so you just reverse it, add spaces in your way and then reverse again to proper initial order. ps [::-1]反转字符串,所以你只需反转它,以你的方式添加空格,然后再次反转到正确的初始顺序。

You need to work out where to start your cursor to print out the correct number at the start您需要确定从哪里开始 cursor 以在开始时打印出正确的数字

string_length = len(binaryString)

# Start position is the remainder when dividing by 4
start_pos = string_length % 4

output_items = []

# Get first item
if start_pos > 0:
 output_items.append(binaryString[0:start_pos])

# Go through the remainder of the string
for i in range(start_pos, string_length, 4):
 output_items.append(binaryString[i:i+4])

print("Binary \t=\t " + ' '.join(output_items))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM