首页 > 解决方案 > 将字符或单词移动到新行

问题描述

给定一个字符串,我如何将部分字符串移入新行。不移动其余的行或字符

'This' and 'this' word should go in the next line
Output:
> and word should go in the next line
  This this

这只是我想要的输出示例,假设单词可能因字符而异。更清楚地说,我在数组中有一些字符串元素,我必须将元素的第二个和第三个单词移动到一个新行并按原样打印该行的其余部分。我试过使用 \n 和 for 循环。但它也会将字符串的其余部分移动到新行

['This and this', 'word should go', 'in the next']
Output:
> This word in
  and this should go the next

所以元素的第二个和第三个单词被移动而不影响该行的其余部分。是否可以在没有太多复杂性的情况下做到这一点?我知道格式方法,但我不知道如何在这种情况下使用它。

标签: python-3.x

解决方案


对于您的第一个示例,如果您事先不知道目标单词的顺序,我会使用字典来存储找到的单词的索引。然后您可以对它们进行排序,以将找到的单词按照它们在文本中出现的顺序放在第二行:

targets = ['this', 'This']
source = 'This and this word should go in the next line.'

target_ixs = {source.find(target): target for target in targets}
line2 = ' '.join([target_ixs[i] for i in sorted(target_ixs)])

line1 = source
for target in targets:
    line1 = line1.replace(target, '')
line1 = line1.replace('  ', ' ').lstrip()

result = line1 + '\n' + line2
print(result)
and word should go in the next line.
This this

您的第二个示例更简单,因为您已经知道要放入第二行的字符串的哪些部分,因此您只需将每个字符串拆分为单词列表并从中选择:

source = ['This and this', 'word should go', 'in the next']

source_lists = [s.split() for s in source]
line1 = ' '.join([source_list[0] for source_list in source_lists])
line2 = ' '.join([' '.join(source_list[1:]) for source_list in source_lists])

result = line1 + '\n' + line2
print(result)
This word in
and this should go the next

推荐阅读