Python--Print打印格式总结(从C借用&Format)

本文作者因使用 VBA 不熟练受虐,决定重新学习 Python。重点介绍了 Python 打印函数,包括字符串、数值、变量的输出,以及格式化输出的多种方式,如类似 C 的 printf 格式化和 format 函数自定义格式,还提及类型转换和 print 不换行的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前上Workshop的时候,被VBA小小的虐了一下,之前感觉很简单的东西,过了很久使用不熟练就会忘记,然后就被虐。。。

老师是一个CS专业的local,感觉很好玩

最后送给我了一句话, Focus more on basic thing.

我觉得大概需要把python再好好捡一遍,加油哟~

写这个总结是因为在基础的打印的时候,突然想起是不是可以用C里面的格式化打印,查了一下果然从C里借用了这部分,且还有更好用的format函数,笔芯!

从我的jupyter notebook 同步过来一波

 千万要记得保存!!!!!不要问我怎么知道的。。。

 #这里要想一下  python里有没有花式打印

python花式打印

缩进要使用4个空格(这不是必须的,但你最好这么做),缩进表示一个代码块的开始,非缩进表示一个代码的结束。没有明确的大括号、中括号、或者关键字。这意味着空白很重要,而且必须要是一致的。第一个没有缩进的行标记了代码块,意思是指函数,if 语句、 for 循环、 while 循环等等的结束。

#输入很简单,加上 input("Press Enter")就可以让程序运行完后停一下
x = input("Please input x:")
input("Press Enter")


输出的 print 函数总结:

1. 字符串和数值类型
可以直接输出

2.变量
无论什么类型,数值,布尔,列表,字典...都可以直接输出
3.格式化输出
类似于C中的 printf
(1). %字符:标记转换说明符的开始
(2). 转换标志:-表示左对齐;+表示在转换值之前要加上正负号;“”(空白字符)表示正数之前保留空格;0表示转换值若位数不够则用0填充
(3). 最小字段宽度:转换后的字符串至少应该具有该值指定的宽度。如果是*,则宽度会从值元组中读出。
(4). 点(.)后跟精度值:如果转换的是实数,精度值就表示出现在小数点后的位数。如果转换的是字符串,那么该数字就表示最大字段宽度。如果是*,那么精度将从元组中读出
(5).字符串格式化转换类型

转换类型          含义

d,i       带符号的十进制整数    *
o         不带符号的八进制
u         不带符号的十进制
x         不带符号的十六进制(小写)
X         不带符号的十六进制(大写)
e         科学计数法表示的浮点数(小写)
E         科学计数法表示的浮点数(大写)
f,F       十进制浮点数
g         如果指数大于-4或者小于精度值则和e相同,其他情况和f相同
G         如果指数大于-4或者小于精度值则和E相同,其他情况和F相同
C         单字符(接受整数或者单字符字符串)
r         字符串(使用repr转换任意python对象)
s         字符串(使用str转换任意python对象)

4.如何让 print 不换行
在Python中总是默认换行的
要想换行你应该写成 print(x,end = '' )

然后很重要一点是类型可以自由地转换,你赋什么值,变量就是什么类型,python会自动帮你管理
整数的输出
直接使用'%d'代替可输入十进制数字:
Python支持将值格式化为字符串。将值插入到%s 占位符的字符串中  
(这个用法 从C借用)
%s%d%f


print("Hello %s, my name is %s" % ('john', 'mike'))
```

    Hello john, my name is mike


```python
#如果您使用int而不是字符串,请使用%d而不是%s
print("My name is %s, and I'm %d years old" %('lulu', 15))


#%s 字符串
string=("hello")  
 
#%s打印时结果是hello  
print ("string=%s" % string)      # output: string=hello  
 
#%2s意思是字符串长度为2,当原字符串的长度超过2时,按原长度打印,所以%2s的打印结果还是hello  
print ("string=%2s" % string)     # output: string=hello  
 
#%7s意思是字符串长度为7,当原字符串的长度小于7时,在原字符串左侧补空格,  
#所以%7s的打印结果是  hello  
print ("string=%7s" % string)  # output: string=  hello  
 
#%-7s意思是字符串长度为7,当原字符串的长度小于7时,在原字符串右侧补空格,  
#所以%-7s的打印结果是  hello  
print( "string=%-7s!" % string) # output: string=hello  !  
 
#%.2s意思是截取字符串的前2个字符,所以%.2s的打印结果是he  
print ("string=%.2s" % string)# output: string=he  
 
#%.7s意思是截取字符串的前7个字符,当原字符串长度小于7时,即是字符串本身,  
#所以%.7s的打印结果是hello  
print ("string=%.7s" % string) # output: string=hello  
 
#%a.bs这种格式是上面两种格式的综合,首先根据小数点后面的数b截取字符串,  
#当截取的字符串长度小于a时,还需要在其左侧补空格  
print ("string=%7.2s" % string)# output: string=     he  
print ("string=%2.7s" % string)# output: string=hello  
print ("string=%10.7s" % string) # output: string=     hello  
 
#还可以用%*.*s来表示精度,两个*的值分别在后面小括号的前两位数值指定  
print ("string=%*.*s" % (7,2,string)  )    # output: string=     he  
```

    string=hello
    string=hello
    string=  hello
    string=hello  !
    string=he
    string=hello
    string=     he
    string=hello
    string=     hello
    string=     he

 

```python
#%d 整型
num=14  
 
#%d打印时结果是14  
print ("num=%d" % num)          # output: num=14  
 
#%1d意思是打印结果为1位整数,当整数的位数超过1位时,按整数原值打印,所以%1d的打印结果还是14  
print ("num=%1d" % num)        # output: num=14  
 
#%3d意思是打印结果为3位整数,当整数的位数不够3位时,在整数左侧补空格,所以%3d的打印结果是 14  
print ("num=%3d" % num  )         # output: num= 14  
 
#%-3d意思是打印结果为3位整数,当整数的位数不够3位时,在整数右侧补空格,所以%3d的打印结果是14_  
print ("num=%-3d" % num)         # output: num=14_  
 
#%05d意思是打印结果为5位整数,当整数的位数不够5位时,在整数左侧补0,所以%05d的打印结果是00014  
print ("num=%05d" % num)         # output: num=00014  
 
#%.3d小数点后面的3意思是打印结果为3位整数,  
#当整数的位数不够3位时,在整数左侧补0,所以%.3d的打印结果是014  
print ("num=%.3d" % num)      # output: num=014  
 
#%.0003d小数点后面的0003和3一样,都表示3,意思是打印结果为3位整数,  
#当整数的位数不够3位时,在整数左侧补0,所以%.3d的打印结果还是014  
print ("num=%.0003d" % num)       # output: num=014  
 
#%5.3d是两种补齐方式的综合,当整数的位数不够3时,先在左侧补0,还是不够5位时,再在左侧补空格,  
#规则就是补0优先,最终的长度选数值较大的那个,所以%5.3d的打印结果还是  014  
print ("num=%5.3d" % num)       # output: num=  014  
 
#%05.3d是两种补齐方式的综合,当整数的位数不够3时,先在左侧补0,还是不够5位时,  
#由于是05,再在左侧补0,最终的长度选数值较大的那个,所以%05.3d的打印结果还是00014  
print ("num=%05.3d" % num)        # output: num=00014  
 
#还可以用%*.*d来表示精度,两个*的值分别在后面小括号的前两位数值指定  
#如下,不过这种方式04就失去补0的功能,只能补空格,只有小数点后面的3才能补0  
print ("num=%*.*d" % (4,3,num))  # output: num= 014
```

    num=14
    num=14
    num= 14
    num=14
    num=00014
    num=014
    num=014
    num=  014
    num=00014
    num= 014

 

```python

# %f 浮点型
import math  
 
#%a.bf,a表示浮点数的打印长度,b表示浮点数小数点后面的精度  
 
#只是%f时表示原值,默认是小数点后5位数  
print ("PI=%f" % math.pi)       # output: PI=3.141593  
 
#只是%9f时,表示打印长度9位数,小数点也占一位,不够左侧补空格  
print ("PI=%9f" % math.pi)      # output: PI=_3.141593  
 
#只有.没有后面的数字时,表示去掉小数输出整数,03表示不够3位数左侧补0  
print ("PI=%03.f" % math.pi)    # output: PI=003  
 
#%6.3f表示小数点后面精确到3位,总长度6位数,包括小数点,不够左侧补空格  
print ("PI=%6.3f" % math.pi)    # output: PI=_3.142  
 
#%-6.3f表示小数点后面精确到3位,总长度6位数,包括小数点,不够右侧补空格  
print ("PI=%-6.3f" % math.pi)   # output: PI=3.142_  
 
#还可以用%*.*f来表示精度,两个*的值分别在后面小括号的前两位数值指定  
#如下,不过这种方式06就失去补0的功能,只能补空格  
print ("PI=%*.*f" % (6,3,math.pi))  # output: PI=_3.142  


```

    PI=3.141593
    PI= 3.141593
    PI=003
    PI= 3.142
    PI=3.142
    PI= 3.142

使用format函数来自定义格式
这里的% 被 {}替换了
不过也更容易被理解Python中格式化输出字符串使用format()函数, 字符串即类, 可以使用方法;
Python是完全面向对象的语言, 任何东西都是对象;字符串的参数
1. 使用{NUM}进行表示,0, 表示第一个参数,1, 表示第二个参数, 以后顺次递加;
2. 使用“:”, 指定代表元素需要的操作, 如”:.3”小数点三位, “:8”占8个字符空间等;
3. 还可以添加特定的字母, 如:
foramt函数更常见的用法其实是str.format(),其基本语法是通过{}和:来代替以前的%
数字     格式     输出     描述
3.141592     {:.2f}     3.14     保留小数点后两位
3.141592     {:+.2f}     +3.14     带符号保留小数点后两位
3.141592     {:.0f}     3     不带小数,四舍五入
3     {:0>2d}     03     数字补零 (填充左边, 宽度为2)
3     {x<4d}     3xxx     数字补x (填充右边, 宽度为4)
123456789     {:,}     123,456,789     千分位隔开
0.38     {:.2%}     38%     百分比格式
1000000000     {:.2e}     1.00e+09     指数记法
11     {:b}     1011     二进制转化

b、d、o、x 分别是二进制、十进制、八进制、十六进制。

如果我们希望保留想要的小数位数,需要这样子:
>>> "{:,.2f}".format(12345678.90)
'12,345,678.90'

>>> "{:,.4f}".format(12345678.90)   #任意几位都行
'12,345,678.9000'

^、<、>分别是居中、左对齐、右对齐,后面带宽度,默认用0 填充,可指定填充方式```python

age = 25
name = 'Caroline'

print('{0} is {1} years old. '.format(name, age))  # 输出参数
print('{0} is a girl. '.format(name))
print('{0:.3} is a decimal. '.format(1 / 3))  # 小数点后三位
print('{0:_^11} is a 11 length. '.format(name))  # 使用_补齐空位
print('{first} is as {second}. '.format(first=name, second='Wendy'))  # 别名替换
print('My name is {0.name}'.format(open('out.txt', 'w')))  # 调用方法
print('My name is {0:8}.'.format('Fred'))  # 指定宽度


```

    Caroline is 25 years old.
    Caroline is a girl.
    0.333 is a decimal.
    _Caroline__ is a 11 length.
    Caroline is as Wendy.
    My name is out.txt
    My name is Fred    .

 

```python

>>> print("{:,.2f}".format(12345678.90))
>>> print("{:,.4f}".format(12345678.90) )  #任意几位都行


```

    12,345,678.90
    12,345,678.9000

 

 

 

import rospy from sensor_msgs.msg import Joy import time import pygame from ElfinRobotMovementHTIC import * class Cmd(object): def __init__(self): self.reset() def reset(self): self.axis0 = 0 self.axis1 = 0 self.axis2 = 0 self.axis3 = 0 self.axis4 = 0 self.axis5 = 0 self.btn0 = 0 self.btn1 = 0 self.btn2 = 0 self.btn3 = 0 self.btn4 = 0 self.btn5 = 0 self.btn6 = 0 self.btn7 = 0 self.btn8 = 0 self.btn9 = 0 self.hat0 = 0 class Service(object): def __init__(self, robot): self.joystick = None self.robot = robot self.cmd = Cmd() def init_joystick(self): pygame.init() self.joystick = pygame.joystick.Joystick(0) self.joystick.init() print("44444444") def test(self,wet): print(wet) def loop(self): air = False while True: self.cmd.reset() pygame.event.pump() for i in range(0, self.joystick.get_numaxes()): val = self.joystick.get_axis(i) if abs(val) < 0.2: val = 0 tmp = "self.cmd.axis" + str(i) + " = " + str(val) if val != 0: exec(tmp) for i in range(0, self.joystick.get_numhats()): val = self.joystick.get_hat(i) tmp = "self.cmd.hat" + str(i) + " = " + str(val) exec(tmp) for i in range(0, self.joystick.get_numbuttons()): if self.joystick.get_button(i) != 0: tmp = "self.cmd.btn" + str(i) + " = 1" exec(tmp) if self.cmd.btn1: #toggle IO air = not air stoprobot(self.robot) #(0:X,1:Y,2:Z,3:A,4:B,5:C) #0=negative;1=positive if self.cmd.btn0 and self.cmd.hat0 == (0, 1): print("value from the hat is,self.cmd.btn0",self.cmd.hat0,self.cmd.btn0) LongJogL(self.robot,2,1) elif self.cmd.btn0 and self.cmd.hat0 == (0, -1): print("value from the hat is,self.cmd.hat0",self.cmd.hat0,self.cmd.btn0) LongJogL(self.robot,2,0) elif self.cmd.hat0 == (0, 1): print("value from the hat is",self.cmd.hat0) self.test("test") LongJogL(self.robot,1,0) elif self.cmd.hat0 == (0, -1): print("value from the hat is",self.cmd.hat0) LongJogL(self.robot,1,1) elif self.cmd.hat0 == (1, 0): print("value from the hat is",self.cmd.hat0) LongJogL(self.robot,0,0) elif self.cmd.hat0 == (-1, 0): print("value from the hat is",self.cmd.hat0) LongJogL(self.robot,0,1) elif self.cmd.axis0 > 0.5 : LongJogL(self.robot,3,1) print("movement in axis0") elif self.cmd.axis0 < -0.5: LongJogL(self.robot,3,0) print("movement in axis0") elif self.cmd.axis1 > 0.5: LongJogL(self.robot,4,1) elif self.cmd.axis1 < -0.5: LongJogL(self.robot,4,0) elif self.cmd.axis2 > 0.5: LongJogL(self.robot,5,1) elif self.cmd.axis2 < -0.5: LongJogL(self.robot,5,0) else: stoprobot(self.robot) def close(self): if self.joystick: self.joystick.quit() if __name__ == "__main__": s = connect('192.168.2.1') s.send(b"ReadRobotState,0,;\n") response = s.recv(1024).decode() # 示例响应: "ReadRobotState,OK,1," print(f"机械臂状态: {response}") service = Service(s) service.init_joystick() try: service.loop() finally: service.close() 以及import math from math import * import math3d as m3d import numpy as np import time import socket import os # import tqdm # #-------------------General Modules import socket import numpy as np import os import math # #-------------------Math and Robot Modules from scipy.spatial.transform import Rotation as R import matplotlib.pyplot as plt # #-------------------Core Robotic Modules ip = "192.168.2.1" port = int("10003") #--------------------------------------------------------------------------------------------------------- #Modules to Make Motion of the Robot with respect to the Robot def connect(ip = "192.168.2.1", port = 10003): """Connect to the robot Args: ip ([String]): [192.168.2.1] port ([Int]): [10003] Returns: [Object]: [soccet communication s] """ try: s = socket.socket() s.settimeout(5) s.connect((ip, int(port))) print('robot connected succesfully to') print('ip - {}'.format(ip), '\n', 'port - {}'.format(port)) return s except Exception as e: print(e) print("cant retrive the Actual Position of the Robot") def LongJogL(s, axis, direction, port=10003, robotID=0): try: data = f"LongJogL,{robotID},{axis},{direction},;\n" # 构建指令 print(f"发送指令: {data.strip()}") # 打印发送的指令 s.send(data.encode()) result = s.recv(1024).decode() # 接收响应(增大缓冲区,避免截断) print(f"机械臂响应: {result.strip()}") # 打印响应 # ... 其他逻辑 ... except Exception as e: print(f"指令发送失败: {e}") # def LongJogL(s, axis,direction, port=10003, robotID=0): # """[Move the robot using Joint Values] # Args: # s ([Object]): [Robot TCP Connection] # angles ([List of Floats]): [Joint angles] # port (int, optional): [Port you got connected to]. Defaults to 10003. # robotID (int, optional): [The unique identifier of the robot]. Defaults to 0. # """ # try: # # x, y, z, rx, ry, rz = tuple(pose) # data = str("LongJogL,{},{},{},;\n".format(robotID, axis,direction)) # # print(data) # data = data.encode() # s.send(data) # result = s.recv(port).decode() # # print('result is',result) # # cut = result.split(',') # # if(cut[1] == "OK"): # # while 1: # # s.send("ReadRobotState,0,;".encode()) # # result = s.recv(port).decode() # # cut = result.split(',') # # # print('cut',cut) # # if(cut[1] == "OK" and cut[2] == "0"): # # break # # elif(cut[1] == "Fail"): # # print(result) # except Exception as e: # print(e) # print("cant retrive the Actual Position of the Robot") # def LongJogL(s, axis, direction, port=10003, robotID=0): # try: # data = str("LongJogL,{},{},{},;\n".format(robotID, axis, direction)) # data = data.encode() # s.send(data) # result = s.recv(1024).decode() # 修改了port为固定1024 # print('result is', result) # if "Fail" in result: # print(f"运动指令失败: {result}") # return False # return True # except Exception as e: # print(f"通信错误: {e}") # return False def stoprobot(s, port=10003, robotID=0): try: data = str("GrpStop,0,;") # print(data) data = data.encode() s.send(data) result = s.recv(port).decode() # print('result is',result) cut = result.split(',') if(cut[1] == "OK"): while 1: s.send("ReadRobotState,0,;".encode()) result = s.recv(port).decode() cut = result.split(',') # print('cut',cut) if(cut[1] == "OK" and cut[2] == "0"): break elif(cut[1] == "Fail"): print(result) except Exception as e: print(e) print("cant stop robot") def check_robot_status(s, robotID=0): """检查机械臂状态""" try: s.send(f"ReadRobotState,{robotID},;\n".encode()) response = s.recv(1024).decode() if "OK,0" in response: return True print(f"机械臂状态异常: {response}") return False except Exception as e: print(f"状态检查错误: {e}") return False def connect(ip="192.168.2.1", port=10003): """增强版连接函数""" try: s = socket.socket() s.settimeout(3.0) # 设置超时 s.connect((ip, port)) # 验证连接 s.send(b"ReadRobotState,0,;\n") if b"OK" in s.recv(1024): print(f"成功连接到机械臂 {ip}:{port}") return s else: s.close() raise Exception("机械臂响应异常") except Exception as e: print(f"连接失败: {e}") return None ;这两个代码实现手柄控制机械臂运动,并借用pygame,TCP通信,你可以完善代码,并且这是两个代码,你需要给我两个代码完善后的完整代码
最新发布
07-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值