在每两个数字之间用 space 格式化字符串
Format a string with a space between every two digits
输入:
字符串 = 53434951
我需要拆分字符串,以便输出为:
53 43 49 51
试试这个:
for i in xrange(0, len(input), 2):
out += input[i:i+2] + " "
您可以使用类似的东西:
s = "534349511"
print ' '.join([s[i:i+2] for i in range(0,len(s),2)])
请注意,这也适用于不均匀长度的列表 - 在 space 之后,您的末尾只有一个数字。
def convert(s):
r = ""
for i, c in enumerate(s):
if i and i %2 == 0:
r += ' '
r += c
return r
我的解决方案不会在末尾打印任何额外的空格。
您也可以使用 re.findall
。
In [5]: import re
In [6]: s = "53434951"
In [7]: print(' '.join(re.findall(r'.{2}', s)))
53 43 49 51
或
使用re.sub
In [9]: print(re.sub(r'(.{2})(?=.)', r' ', s))
53 43 49 51
输入: 字符串 = 53434951
我需要拆分字符串,以便输出为: 53 43 49 51
试试这个:
for i in xrange(0, len(input), 2):
out += input[i:i+2] + " "
您可以使用类似的东西:
s = "534349511"
print ' '.join([s[i:i+2] for i in range(0,len(s),2)])
请注意,这也适用于不均匀长度的列表 - 在 space 之后,您的末尾只有一个数字。
def convert(s):
r = ""
for i, c in enumerate(s):
if i and i %2 == 0:
r += ' '
r += c
return r
我的解决方案不会在末尾打印任何额外的空格。
您也可以使用 re.findall
。
In [5]: import re
In [6]: s = "53434951"
In [7]: print(' '.join(re.findall(r'.{2}', s)))
53 43 49 51
或
使用re.sub
In [9]: print(re.sub(r'(.{2})(?=.)', r' ', s))
53 43 49 51