Skip to content

Commit

Permalink
add 字符串的格式化问题.py
Browse files Browse the repository at this point in the history
  • Loading branch information
24012401 committed Jul 3, 2020
1 parent 1de59dc commit 0d3f21a
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions 字符串和正则表达式/字符串的格式化问题.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# topical: 字符串的格式化问题
# author: Liu Xiaoxia
# time: 2020.07.03

# format是字符串的格式化方法
# format接受位置参数和关键字参数
# 位置参数
print("The {0} {1}: {2}:{3}".format("time", "is", "21", "17"))
# 关键字参数
print("The {a} {b}: {c}:{d}".format(a = "time", b = "is", c = "21", d = "21"))
# 位置参数和关键字参数结合使用,位置参数在前,关键字参数在后,否则报错
print("The {0} {1}: {a}:{b}".format("time", "is", a = "21", b = "22"))
# 位置参数0的特殊使用
# ':'冒号表示格式化符号的开始
# '.2f'表示打印定点数
print('{0:.2f}{1}'.format(21.2659, 'Hz'))

# 字符串格式化符号含义及用法
# %c 格式化字符及其ASCII码
str1 = "%c" % 98
print(str1)
str1 = "%c->%c->%c" % (97, 98, 99)
print(str1)
# %s 格式化字符串
str1 = "%s" % "just a test"
print(str1)
# %d 格式化整数
print("%d + %d = %d" % (21, 44, 21+44))
# %o 格式化无符号八进制数
print("%o" % 10)
# %x 格式化无符号十六进制数
print("%x" % 10)
# %X 格式化无符号十六进制数(大写)
print("%X" % 10)
# %f 格式化定点数,可指定小数点后的精度
print("%.2f" % 21.4914)
# %e 用科学计数法格式化定点数
print("%e" % 21.49144914491449144914)
# %E 和%e相同
print("%E" % 21.491449144914)
# %g 根据值的大小决定使用%f或%e
print("%g" % 21.49144914491449144914)
# %G 和%g相同
print("%G" % 21.491449144914)

# 格式化操作符辅助命令
# m.n m是显示的最小总宽度,n是小数点后的位数
print("%10.2f" % 21.5532)
print("%.2e" % 21.5532)
# - 左对齐
print("%-f" % 21.56)
# + 在正整数前面显示加号+
print("%+d" % 2157)
# # 在八进制数前显示零0,在十六进制数前显示0x或0X
print("%#o" % 15)
print("%#x" % 15)
# 0 显示的数字前面填充零0取代空格
print("%010d" % 22)
print("%-010d" % 22)

0 comments on commit 0d3f21a

Please sign in to comment.