解决Python print输出不换行没空格的问题
作者:heliotrope5 时间:2021-03-21 11:05:57
今天在做编程题的时候发现Python的print输出默认换行输出,并且输出后有空格。
题目要求输出
122
而我的输出是:
1
2
2
于是我百度查到取消print自动换行的方法:就是在print的值后边加逗号,例如print x,
果然,不换行了,但是输出结果仍然不对,要求输出为122,而我的输出为1 2 2
于是我继续百度查方法,发现Python2和Python3的print方法是不同的。Python2的print不用加()可以直接输出,例如print 'hello world', Python3则需要加括号 print("hello world"),而且Python3的print方法是有参数的,比如sep表示字符串之间的连接符,end表示以什么结尾。如果没有设置参数默认sep=‘ ',end='\n',因此我把我的代码改为:
print (i,end=''),但是我发现编译错误,因为我用的是Python2,跑Python2 的print是没有参数的,同理,如果在Python3中使用print x,这种逗号形式,也是编译错误的。
于是我不知道该怎么办了,继续百度查到了:
from __future__ import print_function
只要在程序前加这个就可以在Python2中使用参数了。最后终于正确输出122
后来,我又发现一种方法就是使用
sys.stdout.write()
我把代码改为:
sys.stdout.write(str(i))
也能正确输出122
来源:https://blog.csdn.net/heliotrope5/article/details/78333778
标签:Python,print,换行
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
在django模板中实现超链接配置
2023-03-03 12:22:44
python爬虫请求头的使用
2023-03-21 07:10:23
Python中如何使用if语句处理列表实例代码
2023-11-01 03:12:46
![](https://img.aspxhome.com/file/2023/0/79590_0s.png)
python实现网页录音效果
2022-03-19 08:07:15
![](https://img.aspxhome.com/file/2023/3/118063_0s.jpg)
Pandas对每个分组应用apply函数的实现
2022-01-26 04:02:00
![](https://img.aspxhome.com/file/2023/5/78775_0s.jpg)
Linux ORCLE数据库增量备份脚本
2009-11-21 09:43:00
如何使用 Flask 做一个评论系统
2023-12-08 21:04:48
![](https://img.aspxhome.com/file/2023/8/94128_0s.png)
Python+matplotlib实现简单曲线的绘制
2023-01-05 17:21:27
![](https://img.aspxhome.com/file/2023/2/78492_0s.png)
python config文件的读写操作示例
2022-04-05 07:42:11
python 读写txt文件 json文件的实现方法
2022-01-12 19:42:50
OpenCV实现去除背景识别的方法总结
2021-01-06 23:04:10
![](https://img.aspxhome.com/file/2023/0/83880_0s.jpg)
Python实现输出某区间范围内全部素数的方法
2022-04-25 10:04:50
![](https://img.aspxhome.com/file/2023/8/68318_0s.png)
python生成以及打开json、csv和txt文件的实例
2023-08-05 10:44:49
OpenCV-PS扩散毛玻璃效果的实现代码
2022-03-17 22:45:52
![](https://img.aspxhome.com/file/2023/1/117551_0s.jpg)
python一绘制元二次方程曲线的实例分析
2023-08-23 00:49:56
python字符串不可变数据类型
2021-04-14 23:07:09
详解Python如何实现惰性导入-lazy import
2023-12-22 20:15:43
tensorflow实现图像的裁剪和填充方法
2023-07-11 13:26:23
![](https://img.aspxhome.com/file/2023/0/59820_0s.jpg)
Python绘制正余弦函数图像的方法
2022-09-22 19:59:06
![](https://img.aspxhome.com/file/2023/8/104888_0s.png)
Python面向对象程序设计之私有变量,私有方法原理与用法分析
2022-04-17 01:37:50
![](https://img.aspxhome.com/file/2023/3/69053_0s.png)