Home Common Problem How to write python output statement

How to write python output statement

Jun 20, 2023 am 10:53 AM
python

Python uses the "print()" function when outputting statements. Its syntax is: "print(*object, sep='', end='\n', file=sys.stdout)", "object " is the output object. If you need to output multiple objects, they need to be separated by commas. "sep" is used to separate multiple objects. "end" is the end of the output. The default is "\n". "file" is to be written. file object.

How to write python output statement

The operating system of this tutorial: Windows 10 system, Python version 3.11.2, DELL G3 computer.

When you want to output content in python, you can use the output statement print. We have already mastered the basic output format. In fact, the print() function can output multiple variables at the same time, and it has more rich functions.

1. Overview

print(*object, sep='',end='\n',file=sys.stdout)

object——the output object , if you want to output multiple objects, you need to separate them (comma)

print('abcd','efg')
#结果:abcdefg
Copy after login

sep - used to separate multiple objects

print('abcd','efg',sep=":")
#结果:abcd:efg
Copy after login

end - the end of the output, the default is\n

print('abcd',end='')
print('efg',end='')
#结果:abcdefg 输出不换行
Copy after login

file——The file object to be written

2. Variable output

print can output any type of data

As shown in the figure

age=17
print(age)
#结果:17
name='LIKE'
print(name)
#结果:LIKE
list=[17,'LIKE']
print(list)
#结果:[17, 'LIKE']
tuple=(17,'LIKE')
print(tuple)
#结果:(17, 'LIKE')
dict={'age':17,'name':'LIKE'}
print(dict)
#结果:{'age': 17, 'name': 'LIKE'}
Copy after login

3. Formatted output

There are three formatted outputs of print

1. %

This method comes from the c language, the specific operation is as follows

print('%d'%age)
#十进制 17
print('%o'%age)
#八进制 21
print('%x'%age)
#十六进制 11
print('%.2f'%age)
#保留两位小数 17.00
print('%.2e'%age)
#保留两位小数(用科学计数法) 1.70e+01
print('%.2g'%age)
#保留两位小数(在保证六位有效数字的前提下,使用小数方式,长度超过六位用科学计数法)17
print('%s'%age)
#输出字符串 17
char='P'
print('%c'%char)
#输出单个字符 P
Copy after login

There are others, which are usually difficult to use, so I won’t go into details.

2.str.format()

The basic usage of format is to use {} and: instead of %, but the format function is more powerful than %. Compared with %, it has no limit on the number of parameters. The positions can also be out of order. The main functions of format are as follows:

(1) Indexing, filling and interception

print("{},{}".format(age,name))
#按默认顺序 输出 17,LIKE
print("{1},{0}".format(age,name))
#按索引顺序 输出 LIKE,17
print("{gender}".format(gender='boy'))
#按参数名匹配(参数未确定) 输出boy
print("{0} {2} {1}".format('a','b','c'))
#通过位置填充 输出 a c b
print("年龄:{0[0]} 名字:{0[1]}".format(list))
#按列表索引 输出 年龄:17 名字:LIKE
print("年龄:{0[0]} 名字:{0[1]}".format(tuple))
#按元组索引 输出 年龄:17 名字:LIKE
print("年龄:{age} 名字:{name}".format(**dict))
#按字典设置 输出 年龄:17 名字:LIKE
print("{:.2}".format(list[1]))
#截取字符串前5个字符 输出LI
#索引和参数可以混搭(但是命名参数得写到最后),索引和默认不行
Copy after login

(2) Type conversion

print("我的名字是{!s}".format("LIKE"))
#相当于str() 输出我的名字是LIKE
print("我{!r}岁".format("17"))
#相当于repr() 输出我'17'岁
Copy after login

(3) Format Number

print('{:b}'.format(age))
 #输出二进制 10001
print('{:d}'.format(age)) 
#输出十进制 17
print('{:o}'.format(age))
#输出八进制 21
print('{:x}'.format(age))
#输出十六 进制 11
print("{:.2f}".format(17.0000))
#保留两位小数 输出17.00
print("{:+},{:+},{: },{: }".format(-17,17,-17,17))
#在正数前加+  在正数前加空格 输出 -17,+17,-17, 17
print("{:,}".format(5201314))
#用逗号做千位分隔符 输出 5,201,314
print("{:.2%}".format(0.9999))
#表示一个小数点后留两位的百分比 输出 99.99%
Copy after login

(4) Alignment

print("{:*>5}".format("LIKE"))
#右对齐 宽度为5,不足用‘>’前的字符(只能为字符)补齐,默认为空格 输出 *LIKE
print("{:*<5}".format("LIKE"))
#左对齐 输出LIKE*
print("{:*^10}".format("LIKE"))
#居中 输出***LIKE***
Copy after login

3.f"{}"

Mainly call existing elements

def function():
    return "LIKE"
print(f"年龄:{age},姓名:{name}")
#调用变量 输出 年龄:17,姓名:LIKE
print(f"年龄:{list[0]},姓名:{list[1]}")
#调用列表元素 输出 年龄:17,姓名:LIKE
print(f"年龄:{tuple[0]},姓名:{tuple[1]}")
#调用元组元素 输出 年龄:17,姓名:LIKE
print(f"年龄:{dict[&#39;age&#39;]},姓名:{dict[&#39;name&#39;]}")
#调用字典元素 输出 年龄:17,姓名:LIKE
print(f"{1+1}")
#调用并计算表达式 输出 2
print(f"姓名:{function()}")
#调用并计算函数 输出 姓名:LIKE
Copy after login

4. Attachment Picture

from os import sep
#print(*object, sep='',end='\n',file=sys.stdout)
print(&#39;abcd&#39;,&#39;efg&#39;)
#结果:abcdefg
print(&#39;abcd&#39;,&#39;efg&#39;,sep=":")
#结果:abcd:efg
print(&#39;abcd&#39;,end=&#39;&#39;)
print(&#39;efg&#39;,end=&#39;&#39;)
#结果:abcdefg 输出不换行
 
age=17
print(age)
#结果:17
name=&#39;LIKE&#39;
print(name)
#结果:LIKE
list=[17,&#39;LIKE&#39;]
print(list)
#结果:[17, &#39;LIKE&#39;]
tuple=(17,&#39;LIKE&#39;)
print(tuple)
#结果:(17, &#39;LIKE&#39;)
dict={&#39;age&#39;:17,&#39;name&#39;:&#39;LIKE&#39;}
print(dict)
#结果:{&#39;age&#39;: 17, &#39;name&#39;: &#39;LIKE&#39;}
print(&#39;%d&#39;%age)
#十进制 17
print(&#39;%o&#39;%age)
#八进制 21
print(&#39;%x&#39;%age)
#十六进制 11
print(&#39;%.2f&#39;%age)
#保留两位小数 17.00
print(&#39;%.2e&#39;%age)
#保留两位小数(用科学计数法) 1.70e+01
print(&#39;%.2g&#39;%age)
#保留两位小数(在保证六位有效数字的前提下,使用小数方式,长度超过六位用科学计数法)17
print(&#39;%s&#39;%age)
#输出字符串 17
char=&#39;P&#39;
print(&#39;%c&#39;%char)
#输出单个字符 P
 
print("{},{}".format(age,name))
#按默认顺序 输出 17,LIKE
print("{1},{0}".format(age,name))
#按索引顺序 输出 LIKE,17
print("{gender}".format(gender=&#39;boy&#39;))
#按参数名匹配(参数未确定) 输出boy
print("{0} {2} {1}".format(&#39;a&#39;,&#39;b&#39;,&#39;c&#39;))
#通过位置填充 输出 a c b
print("年龄:{0[0]} 名字:{0[1]}".format(list))
#按列表索引 输出 年龄:17 名字:LIKE
print("年龄:{0[0]} 名字:{0[1]}".format(tuple))
#按元组索引 输出 年龄:17 名字:LIKE
print("年龄:{age} 名字:{name}".format(**dict))
#按字典设置 输出 年龄:17 名字:LIKE
print("{:.2}".format(list[1]))
#截取字符串前5个字符 输出LI
#索引和参数可以混搭(但是命名参数得写到最后),索引和默认不行
 
print("我的名字是{!s}".format("LIKE"))
#相当于str() 输出我的名字是LIKE
print("我{!r}岁".format("17"))
#相当于repr() 输出我&#39;17&#39;岁
 
print(&#39;{:b}&#39;.format(age))
 #输出二进制 10001
print(&#39;{:d}&#39;.format(age)) 
#输出十进制 17
print(&#39;{:o}&#39;.format(age))
#输出八进制 21
print(&#39;{:x}&#39;.format(age))
#输出十六 进制 11
print("{:.2f}".format(17.0000))
#保留两位小数 输出17.00
print("{:+},{:+},{: },{: }".format(-17,17,-17,17))
#在正数前加+  在正数前加空格 输出 -17,+17,-17, 17
print("{:,}".format(5201314))
#用逗号做千位分隔符 输出 5,201,314
print("{:.2%}".format(0.9999))
#表示一个小数点后留两位的百分比 输出 99.99%
 
print("{:*>5}".format("LIKE"))
#右对齐 宽度为5,不足用‘>’前的字符(只能为字符)补齐,默认为空格 输出 *LIKE
print("{:*<5}".format("LIKE"))
#左对齐 输出 LIKE*
print("{:*^10}".format("LIKE"))
#居中 输出 ***LIKE***
 
def function():
    return "LIKE"
print(f"年龄:{age},姓名:{name}")
#调用变量 输出 年龄:17,姓名:LIKE
print(f"年龄:{list[0]},姓名:{list[1]}")
#调用列表元素 输出 年龄:17,姓名:LIKE
print(f"年龄:{tuple[0]},姓名:{tuple[1]}")
#调用元组元素 输出 年龄:17,姓名:LIKE
print(f"年龄:{dict[&#39;age&#39;]},姓名:{dict[&#39;name&#39;]}")
#调用字典元素 输出 年龄:17,姓名:LIKE
print(f"{1+1}")
#调用并计算表达式 输出 2
print(f"姓名:{function()}")
#调用并计算函数 输出 姓名:LIKE
Copy after login

The above is the detailed content of How to write python output statement. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.