Python字符串格式化

在很多情况下,我们需要对字符进行格式化,格式化的方法也有许多中,我们可以选择自己比较喜欢的方法。这里我们主要基于Python3.6以上的版本

1、字符串拼接的方法
str1 +str(目标字段)+str2
这个比较交单,直接拼接就行。

2、传统型%
语言比较苍白,直接上例子:
传入整数

a = 100
print( "hello ,this is %d"  %a)

hello ,this is 100

传入浮点型

a = 19.89
print( "hello ,this is %0.1f"  %a)

hello ,this is 19.9

传入转化成百分比的形式:

a = 0.1989
print( "hello ,this is %0.1f%%"  %(a*100))

hello ,this is 19.9%

传入字符串形式:

a = 'SAME'
print( "hello ,this is %s"  %a)

hello ,this is SAME

3、使用format,python2.6开始支持
(1)format 函数可以接受不限个参数,位置可以不按顺序。

“{} {}”.format(“hello”, “world”) # 不设置指定位置,按默认顺序
‘hello world’

“{0} {1}”.format(“hello”, “world”) # 设置指定位置
‘hello world’

“{1} {0} {1}”.format(“hello”, “world”) # 设置指定位置
‘world hello world’

(2)也可以设置参数:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
print("网站名:{name}, 地址 {url}".format(name="我是菜鸟", url="www.com"))
 
# 通过字典设置参数
site = {"name": "我是菜鸟", "url": "www.com"}
print("网站名:{name}, 地址 {url}".format(**site))
 
# 通过列表索引设置参数
my_list = ['我是菜鸟', 'www.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

(3)传入对象

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class AssignValue(object):
    def __init__(self, value):
        self.value = value
my_value = AssignValue(6)
print('value 为: {0.value}'.format(my_value))  # "0" 是可选的

(4)数字格式化

print("{:.2f}".format(3.1415926));

在这里插入图片描述
4、使用’f-strings’
f-string 是 python3.6 之后版本添加的,称之为字面量格式化字符串,是新的格式化字符串的语法。要使用f-strings,只需在字符串前加上f:
(1)基本使用方法

a="hello"
f"{0.235}{a}"  ##'0.235hello'

(2)支持对象运算等

    print(f"{name[i]}变量个数{v.shape[1]}个:去掉全部缺失变量,剩余{v.dropna(axis=1,how='all').shape[1]}个变量")

数字操作:

# 小数精度
PI = 3.141592653
f"Pi is {PI:.2f}"
'Pi is 3.14'

# 进制转换
f'int: 31, hex: {31:x}, oct: {31:o}'
'int: 31, hex: 1f, oct: 37'

fs-str详细可参考:https://blog.csdn.net/qq_29027865/article/details/84850683

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值