python-3.x - 将字符或单词移动到新行
问题描述
给定一个字符串,我如何将部分字符串移入新行。不移动其余的行或字符
'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
所以元素的第二个和第三个单词被移动而不影响该行的其余部分。是否可以在没有太多复杂性的情况下做到这一点?我知道格式方法,但我不知道如何在这种情况下使用它。
解决方案
对于您的第一个示例,如果您事先不知道目标单词的顺序,我会使用字典来存储找到的单词的索引。然后您可以对它们进行排序,以将找到的单词按照它们在文本中出现的顺序放在第二行:
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
推荐阅读
- makefile - 乐鑫 ESP8266 NONOS_SDK - Makefile
- javascript - 如何从第二个选项卡窗口打开第一个选项卡窗口的 url 页面?
- python - 寻找迷宫的最短或最长解决方案
- javascript - jQuery没有从id读取下拉框文本
- swift - 在 ARkit 中永久显示 3D 对象
- jquery - 添加 jQuery 移动库后,jQuery replaceWith 抛出错误
- templates - VueJS:外部模板文件(使用变量)
- listview - Flutter的ListView如何设置缓存大小?
- java - 将字符串值从一个函数传递到另一个函数而不将该字符串作为参数传递
- ios - 如何解析数据然后将其加载到pickerView中?