Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 每80个空格拆分一个字符串_Python - Fatal编程技术网

Python 每80个空格拆分一个字符串

Python 每80个空格拆分一个字符串,python,Python,例如,我有一个6400个数字的字符串,我想将其转换为80x80字符串格式 string1 = '1 2 3 4 5 6 7 8 9' 我想做的是: string2 = '''1 2 3 4 5 6 7 8 9''' *数字的长度也不同 我尝试过使用split(),但我不知道如何“计算”空格数并将其放入一个大字符串中可以通过按设置的块大小对字符串进行切片来实现 # Print a new line every 6 characters # C

例如,我有一个6400个数字的字符串,我想将其转换为80x80字符串格式

string1 = '1 2 3 4 5 6 7 8 9'
我想做的是:

string2 = '''1 2 3
             4 5 6
             7 8 9'''
*数字的长度也不同


我尝试过使用split(),但我不知道如何“计算”空格数并将其放入一个大字符串中

可以通过按设置的块大小对字符串进行切片来实现

# Print a new line every 6 characters
# Change this as needed
chunk_size = 6

# The string to split
s =  '1 2 3 4 5 6 7 8 9'

# Iterate over a range of numbers 0 to the length of the string
# with a step size of `chunk_size`
# With `chunk_size` as 6, the range will look like
# [0, 6, 12]
for i in range(0, len(s), chunk_size):
    # Slice the string from the current index
    # to the current index plus the chunk size
    # ie: [0:6], [6:12], [12:18]
    print(s[i:i+chunk_size])

print()

# To do this with list comprehension
s2 = "\n".join(s[i:i+chunk_size] for i in range(0, len(s), chunk_size))
print(s2)

# Ouptut:
# 1 2 3
# 4 5 6
# 7 8 9
或者,如果你有可变长度的数字,按照Austin所说的做,并在字符串的拆分版本上应用相同的概念

chunk_size = 3
s = '10 20 30 4 5 6 7 8 9'.split()

for i in range(0, len(s), chunk_size):
    print(" ".join(s[i:i+chunk_size]))

print()

s2 = "\n".join(" ".join(s[i:i+chunk_size]) for i in range(0, len(s), chunk_size))
print(s2)

# Output:
# 10 20 30
# 4 5 6
# 7 8 9

您可以在空间上拆分并在其中进行迭代,生成给定大小的块:

string1 = '1 2 3 4 5 6 7 8 9'

size = 3
splits = string1.split()

print('\n'.join(' '.join(splits[j] for j in range(i, i+size)) for i in range(0, len(splits), size)))

# 1 2 3
# 4 5 6                                                                                      
# 7 8 9

可变长度数字?只需使用正则表达式

import re

string1 = '1 22 333 4444 55555 666666 77777777 888888888 9999999999'
string2 = '\n'.join(re.findall('((?:\S+ ){2}\S+)', string1))
(?:)
创建了一个组,您可以重复该组,但不能在匹配中捕获它,这使得直接连接成为可能。没有它,你会得到元组

re.sub
也可以工作

string2 = re.sub('((\S+ ){2}\S+) ', lambda m: m.group()+'\n', string1)
当然,您可以使用
{79}
而不是
{2}
,后者重复
'\S+'
模式(一个或多个非空白字符后跟一个空格),因此您不必将其写出。

split()
不添加换行符,它将字符串拆分为列表,这里不需要这些列表。您可以将强切片(:)与for循环一起使用。但别忘了字符串是不可变的。您需要在新变量上串联。您应该使用
split()
,否则它对字符串中的多个数字失败,例如:10 11 12。