繁体   English   中英

对于 python 字符串,如何将每一行打印为新行?

[英]for python string how can I print each line as a new line?

我有一个奇怪的问题。 我拨打 API 并得到以下结果:

1. Increase the use of alternative fuels: The aviation industry can reduce its carbon emissions by increasing the use of alternative fuels such as biofuels, hydrogen, and synthetic fuels.
2. Improve aircraft efficiency: The aviation industry can reduce its carbon emissions by improving the efficiency of aircraft through the use of advanced materials, aerodynamic designs, and lighter engines.
3. Utilize air traffic management systems: The aviation industry can reduce its carbon emissions by utilizing air traffic management systems that optimize flight paths and reduce fuel consumption.
4. Invest in research and development: The aviation industry can reduce its carbon emissions by investing in research and development of new technologies that can reduce emissions.
5. Increase the use of renewable energy: The aviation industry can reduce its carbon emissions by increasing the use of renewable energy sources such as solar, wind, and geothermal.
6. Implement carbon offset programs: The aviation industry can reduce its carbon emissions by implementing carbon offset programs that allow airlines to purchase carbon credits to offset their emissions.

我正在尝试将每一行打印为自己的行(我想稍后将其保存到变量中)但它不起作用。 当我尝试时:

for item in reponse:
  print("*")
  print(item)

它一次只打印 1 个字符。 我该怎么做才能一次保存每一行? 我试图查看原始字符串数据,但我不确定它如何或为什么要换行。

我能做什么?

肯定是response是一个包含所有行的大字符串,所以当你遍历它时,你一次得到一个字符。

字符串有一个splitlines()方法,可以根据换行符将一个大字符串拆分成单独的行。

试试这个:

for item in response.splitlines():

看来您的 API 返回给您的是一个包含多行的字符串。 有很多方法可以处理这个问题。 一种是对结果使用 splitlines() 方法,例如:

for item in response.splitlines():
    print(item) # which is a single line

您可能还会遇到一些奇怪的行尾字符,具体取决于格式化的响应文本是针对 Windows、Mac 还是 Linux。

还要记住, splitlines()包括一个选项,可以在每行的末尾包含或排除换行符。

这是来自 Python 的参考资料:

str.splitlines(keepends=False) 返回字符串中的行列表,在行边界处断开。 换行符不包含在结果列表中,除非给出了 keepends 并且为真。

此方法在以下行边界上拆分。 特别是,边界是通用换行符的超集。

表示

描述

\n

换行

\r

回车

\r\n

回车+换行

\v 或 \x0b

行制表

\f 或 \x0c

换页

\x1c

文件分隔符

\x1d

组分隔符

\x1e

记录分隔符

\x85

下一行(C1 控制代码)

行分隔符

段落分隔符

在 3.2 版更改:\v 和 \f 添加到行边界列表。

例如:

'ab c\n\nde fg\rkl\r\n'.splitlines() ['ab c', '', 'de fg', 'kl'] 'ab c\n\nde fg\rkl\r\ n'.splitlines(keepends=True) ['ab c\n', '\n', 'de fg\r', 'kl\r\n'] 与 split() 在给定分隔符字符串 sep 时不同,这个方法为空字符串返回一个空列表,并且终端换行符不会导致额外的行:

"".splitlines() [] "One line\n".splitlines() ['One line'] 为了比较,split('\n') 给出:

''.split('\n') [''] '两行\n'.split('\n') ['两行', '']

你能做的,不是最好的解决方案,是制作一个字符串,然后在每行的末尾使用 /n,例如:

代码:

string = "Hello World/nIts a great day" 打印(字符串)

Output:

你好世界这是美好的一天

在单个字符串中创建新行的 \n 字符。 这称为换行符。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM