python - 如何在保留 \n 的同时拆分字符串
问题描述
我想写每个项目的第一个字母,而换行符保持不变,但是当我将列表转换为字符串时,它写在一行中。像这样"I w t w f l o e I w l s s"
,但我希望输出看起来像这样"I w t \n w t f l \n o e i \n w l \n s s"
。
r = '''I want to
write the first letter
of every item
while linebreak
stay same'''
list_of_words = r.split()
m = [x[0] for x in list_of_words]
string = ' '.join([str(item) for item in m])
print(string)
解决方案
您正在做的是一次拆分所有行,因此您丢失了每行的信息。您需要创建列表列表以保留行信息。
当您提供no argument
means split according to any whitespace
时,这意味着两者' ' and '\n'
。
r = '''I want to
write the first letter
of every item
while linebreak
stay same'''
list_of_words = [i.split() for i in r.split('\n')]
m = [[y[0] for y in x] for x in list_of_words]
string = '\n'.join([' '.join(x) for x in m])
print(string)
I w t
w t f l
o e i
w l
s s
推荐阅读
- node.js - 如何访问在不同容器上运行的两个快速服务器之间的不同端点
- swift - 在 init() 构造函数中初始化的带有 @State 的 SwiftUI 视图
- android - 无法在 android studio 3.6 中进行 git pull
- android - 适用于 Android 和 iOS 的应用内购买撤销机制
- ios - 需要在 Swift 中以编程方式进行监督和非监督
- r - Aggregate rows with conditions, sum quantitative values, and keep character values of the max
- android - APK分析使用MobSF(Mobile-Security-Framework-MobSF)框架,显示代码分析为空
- python - 用反斜杠 pandas 分隔列值
- android - Android Q 中的内部应用程序音频捕获不适用于某些 android 设备
- powershell - 在 Windows Server 2008 R2 中使用 New-WebVirtualDirectory