python print 所有用法
时间: 2023-05-23 16:01:10 浏览: 71
Python中的print能够把想要输出的信息打印到控制台中。以下是一些使用print的例子:
1. 将字符串打印到控制台上:
print("Hello, world!")
2. 可以打印多个变量,使用逗号进行分割:
x = 1
y = 2
print("x is", x, "and y is", y)
3. 使用end关键字指定结束时要用的字符(默认是换行符)。
for i in range(5):
print(i, end=" ")
4. 将输出重定向到文件中,使用文件对象就可以了。
with open('output.txt', 'w') as f:
print('Hello, world!', file=f)
相关问题
python print打印变量所有用法
在 Python 中,使用 `print()` 函数可以将字符串或变量的值输出到控制台。下面是 `print()` 函数打印变量的几种用法:
1. 输出变量的值:
```python
x = 10
print(x) # 输出:10
```
2. 使用格式化字符串输出变量的值:
```python
x = 10
print(f"The value of x is {x}") # 输出:The value of x is 10
```
3. 将多个变量的值一起输出:
```python
x = 10
y = 20
print(x, y) # 输出:10 20
```
4. 将多个变量的值格式化后一起输出:
```python
x = 10
y = 20
print(f"The value of x is {x}, and the value of y is {y}") # 输出:The value of x is 10, and the value of y is 20
```
5. 使用不同的分隔符将多个变量的值输出:
```python
x = 10
y = 20
print(x, y, sep="---") # 输出:10---20
```
6. 输出变量的类型:
```python
x = 10
print(type(x)) # 输出:<class 'int'>
```
7. 将变量的值保存到文件中:
```python
x = 10
with open("output.txt", "w") as f:
print(x, file=f)
```
python print函数用法
print()函数是Python中最常用的内置函数之一,用于将指定的内容打印输出到控制台。它的语法如下:
```python
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
```
其中,`*objects`是要打印输出的内容,可以是一个或多个对象,用逗号分隔。`sep`参数用于指定多个对象之间的分隔符,默认为一个空格。`end`参数用于指定打印输出的结尾字符,默认为换行符`\n`。`file`参数用于指定输出的文件对象,默认为标准输出流`sys.stdout`。`flush`参数用于指定是否立即刷新输出,默认为False。
下面是一些示例:
```python
print("Hello, World!") # 输出:Hello, World!
print("The answer is", 42) # 输出:The answer is 42
print("Hello", "World", sep="-") # 输出:Hello-World
print("Hello", end="") # 输出:Hello(结尾没有换行符)
print("World") # 输出:World
```
需要注意的是,print()函数可以打印输出各种类型的对象,包括字符串、数字、列表、字典等。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)