def split_string(s,num):
'''
1. 定义一个函数,接受一个字符串作为参数。
2. 遍历字符串中的每个字符,判断是中文字符还是英文字符,根据字符类型累加字符长度。
3. 如果字符长度达到10,就将该行字符串添加到结果列表中,并将当前行字符串清空。
4. 最后将剩余的字符串添加到结果列表中。
5. 将结果列表中的每个字符串用换行符连接起来,返回最终结果。
'''
result = []
line = ''
length = 0
for c in s:
if length + (2 if ord(c) > 127 else 1) > num:
result.append(line)
line = ''
length = 0
line += c
length += 2 if ord(c) > 127 else 1
result.append(line)
return '\n'.join(result)
s = '''这是一段长文本,我们需要将它转换为多行文本,从而实现不同场合下的应用!This is a long text, we need to convert it into multi line text, so as to realize the application'''
print(split_string(s,20))
最新的Python长字符串变成规定长度的多行字符串
于 2023-03-21 16:14:10 首次发布