Python 格式化字符串

2023-11-14  本文已影响0人  Bioinfor生信云

Python的格式化字符串是一种用于在字符串中插入变量或表达式的强大工具。它允许你以一种清晰和简洁的方式将数据嵌入到字符串中。

常用格式

数字 格式 输出 描述
'total len' {:s} total len 字符串
3.1415926 {:.2f} 3.14 保留小数点后两位
3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
-1 {:+.2f} -1.00 带符号保留小数点后两位
2.71828 {:.0f} 3 不带小数
5 {:0>2d 05 数字补零(填充左边,宽度为 2)
5 {:x<4d} 5xxx 数字补 x(填充右边,宽度为 4)
10 {:x<4d} 10xx 数字补 x(填充右边,宽度为 4)
13 {:>10d} 13 右对齐(默认,宽度为10)
13 {:<10d} 13 左对齐(宽度为10)
13 {:^10d} 13 中间对齐(宽度为10)
1000000 {:,} 1,000,000 以逗号分隔的数字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指数记法

示例

total_len = 876487644
avg_len = 876.487644
gc_count = 0.5
longest_id = 'chr1'
longest_len = 755

使用字符串连接

print('序列的总长为:'+ str(total_len))
print('序列平均长度为:'+ str(avg_len))
print('序列GC含量为:'+ str(gc_count))
print('最长染色体为:'+ longest_id + ',其长度为:'+ str(longest_len))

##序列的总长为:876487644
##序列平均长度为:876.487644
##序列GC含量为:0.5
##最长染色体为:chr1,其长度为:755

使用格式化字符串

print('序列的总长为:{:.2f}'.format(total_len))
print('序列平均长度为:{:.2f}'.format(avg_len))
print('序列GC含量为:{:.2%}'.format(gc_count))
print('最长染色体为{1},其长度为{0}'.format(longest_len,longest_id))

##序列的总长为:876487644.00
##序列平均长度为:876.49
##序列GC含量为:50.00%
##最长染色体为chr1,其长度为755

总结:{位置:填充字符对齐方式宽度[.精度]类型}

欢迎关注Bioinfor 生信云!

上一篇 下一篇

猜你喜欢

热点阅读