社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

避免Python中的尾随换行符[duplicate]

Shreya • 5 年前 • 1612 次点击  

这个问题已经有了答案:

我现在正在做一个项目,作为其中一个特性,我应该遍历一个列表并以不同的行输出项目。

代码如下所示:

dictionary = {'key0': sorted([item + "\n" 
              for item in mylist}])

print(x[1]) for x in dictionary.items()

但是,每次都会留下一个尾随的换行符。

想要这个吗?

string = ''

otherlist = sorted([item + "\n" for item in mylist])

for i in range(len(otherlist)):
    string.join(sorted[i])

string.rstrip()

print(string)

有没有更好的方法可以做到这一点?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50484
 
1612 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Soviut
Reply   •   1 楼
Soviut    6 年前

与其在列表理解中添加换行符,不如用换行符将列表连接起来。

lines = '\n'.join(otherlist)
Netwave
Reply   •   2 楼
Netwave    6 年前

使用 str.join :

print("".join(x[1] for x in dictionary.items()))