简体   繁体   English

如何打印由一行分隔的许多预先存在的字符串?

[英]How can I print many pre-existing strings separated by a line?

I'm working on a project and I have a bunch of already defined strings with various names我正在做一个项目,我有一堆已经定义好的不同名称的字符串

I want to print all of them, each one starting on a new line.我想打印所有这些,每一个都从一个新行开始。 What I have right now is this:我现在拥有的是这样的:

print(line1 + '\n' + line2 + '\n' + line3 ... )

Don't get me wrong, it works, but I was just wondering if there was an easier way to do it that would physically shorten the line.不要误会我的意思,它有效,但我只是想知道是否有更简单的方法可以在物理上缩短线路。 Thanks!谢谢!

You can use the .join method:您可以使用.join方法:

>>> line1 = "a"
>>> line2 = "b"
>>> line3 = "c"
>>> "\n".join([line1, line2, line3])
'a\nb\nc'
>>> print("\n".join([line1, line2, line3]))
a
b
c

Or, you can use the sep parameter of print if you don't need to store the string:或者,如果不需要存储字符串,可以使用printsep参数:

>>> print(line1, line2, line3, sep="\n")
a
b
c

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Flask,python和postgresql如何连接到预先存在的数据库? - using Flask, python and postgresql how can I connect to a pre-existing database? 如何将预先存在的 python 项目导入 Eclipse? - How do I import a pre-existing python project into Eclipse? 如何重新输入预先存在的 django 应用程序 - How to reenter a pre-existing django app 如何在sqlalchemy中更改现有数据库表的两个不同的列标题? - How do I alter two different column headers of a pre-existing database table in sqlalchemy? 我如何将一个数字插入到预先存在的脚本中并重复 3544 次 - How would I insert a number into a pre-existing script in and repeat 3544 times 如何编写 Python 代码来创建一个字典,该字典包含来自一个预先存在的字典的元素,该字典采用一个键和多个值? - How to make Python code that creates a dictionary that contains elements from a pre-existing dictionary that takes one key and many values? 如何从文本文件中打印字符串,在 Python 中以新行分隔 - How to print strings from a text file,separated by new line in Python 如何加载预先存在的数据烧瓶-sqlalchemy - how to load pre-existing data flask-sqlalchemy 如何在 Django 中创建预先存在模型的实例? - How to create an instance of a pre-existing model in django? 如何使用 Python 在 Selenium 中使用预先存在的条目覆盖特定字段 - How to Overwrite a Specific Field with Pre-existing Entry in Selenium with Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM