在每20个字符后添加换行符,并将结果保存为新字符串



我有一个字符串变量input = "A very very long string from user input",如何循环遍历字符串并在20个字符后添加换行符n,然后将格式化的字符串保存在变量new_input中?

到目前为止,我只能获得像input[0:20]这样的前20个字符,但你如何通过整个字符串做到这一点,并在这一点上添加换行符?

您可能想做一些类似的事情

inp = "A very very long string from user input"
new_input = ""
for i, letter in enumerate(inp):
if i % 20 == 0:
new_input += 'n'
new_input += letter
# this is just because at the beginning too a `n` character gets added
new_input = new_input[1:] 

除了list comprehension+join方法(顺便说一下,这非常方便(,您还可以在regex:中使用python构建

import re
'n'.join(re.findall('.{1,20}', string))

使其通用于每个nth字符:

n = 20
'n'.join(re.findall('.{1,%i}' % n, string))

正如@CrazyChuck正确地假设的那样,这可能比列表理解方法需要更长的时间。例如,给定一个包含10亿个字符的字符串(例如string = 'A' * 10**9(,使用list comprehension需要10.6秒,而使用regex方法需要12.6秒。也许更大的字符串有很大的区别,但对于没有那么大的字符串来说这不是问题。

您可以访问适当长度的切片,而不是逐个遍历每个字符。

text = "A very very long string from user input"
line_length = 5
lines = []
for i in range(0, len(text), line_length):
lines.append(text[i:i+line_length] + 'n')
print(''.join(lines))

您可以将for循环替换为列表理解:

text = "A very very long string from user input"
line_length = 5
lines = [text[i:i+line_length] + 'n' for i in range(0, len(text), line_length)]
print(''.join(lines))

打印:

A ver
y ver
y lon
g str
ing f
rom u
ser i
nput

line_length更改为20以获得实际的较长输入。

注意:如果最后一行少于20个字符,那么对问题的字面解读将省略最后一行换行符('n'(。如果你愿意,你可以这样做,但如果你要把它打印到屏幕上或保存到文件中,你可能希望最后一行有一个换行符,即使它是一个较短的余数。

假设您需要为每个第n个字符拆分一个字符串。

然后你可以使用列表理解。这将获得字符串列表,您可以简单地使用join方法将其连接起来。像这样:

some_str: str = "A very very long string from user input"
n: int = 20
splitted_str: List[str] = [some_str[i:i+n] for i in range(0, len(some_str), n)]
result: str = "n".join(splitted_str)

这里有一个基本且详细说明的方法,可以为每20个字符添加一行新行。

user_input = "A very very long string from user input" #1
char_count = 0 #2
new_input_list = [] #3
user_new_input = '' #4
for c in user_input: #5 
char_count += 1 #6 
new_input_list.append(c) #7 
if char_count == 20: #8 
new_input_list.append('n') #9 
char_count = 0 #10 
print(user_new_input.join(new_input_list)) #11 
#1 user_input can't use input because that is a reserved word in python 
#2 used to keep track of number of chars looped through
#3 list to append the chars looped through and the 'n' (new line)
#4 used to hold the joining of the chars and new line in new_input_list
#5 for loop to loop through the user_input string
#6 counts the number of chars by counting the number of loops
#7 appends chars to list
#8 enter condition that once 20 loops(chars) have passed
#9 appends new line to list
#10 resets the char_count to 0 so condition can be used on the next 20 chars
#11 prints out the joined list to a string called user_new_input

最新更新