无名商城论坛

搜索
查看: 306|回复: 0

[其他技术] 【HC】Python format 格式化函数

[复制链接]

1万

主题

1万

帖子

3万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
32464
发表于 2022-5-8 18:35:07 | 显示全部楼层 |阅读模式


一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
基本语法是通过 {} 和 : 来代替以前的 % 。

format 函数可以接受不限个参数,位置可以不按顺序。

这么玩:

# 不设置指定位置,按默认顺序

expenses = (
    ['Rent', 1000],
    ['Gas',   100],
    ['Food',  300],
    ['Gym',    50],
)
for x, i in expenses:
    print('a:{} b:{}'.format(x, i))




结果:
a:Rent b:1000
a:Gas b:100
a:Food b:300
a:Gym b:50
# 设置指定位置

expenses = (
    ['Rent', 1000],
    ['Gas',   100],
    ['Food',  300],
    ['Gym',    50],
)
for x, i in expenses:
    print('a:{0} b:{1}'.format(x, i))

  结果:a:Rent b:1000
       a:Gas b:100
       a:Food b:300
       a:Gym b:50
   print('a:{0} b:{1}'.format(x, i))
  
  结果:a:1000 b:Rent
       a:100 b:Gas
       a:300 b:Food
       a:50 b:Gym

#也可以设置参数:

print("网站名:{name}, 地址 {url}".format(name="xxx", url="www.xxx.com"))


网站名:xxx, 地址 www.xxx.com
# 通过字典设置参数

data = {'name':'xxx', 'url':'www.xxx.com'}
print("网站名:{name}, 地址 {url}".format(**data))
# 通过列表索引设置参数


my_list = ['xxx', 'www.xxx.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的
#也可以向 str.format() 传入对象

class AssignValue(object):
    def __init__(self, num):
        self.num = num

my_num = AssignValue(6)
print('num 为: {0.num}'.format(my_num))  # "0" 是可选的
print('num 为: {my_num.num}'.format(my_num=my_num))

# value 为: 6
# value 为: 6
粘过来的:
expenses = (
    ['Rent', 1000],
    ['Gas',   100],
    ['Food',  300],
    ['Gym',    50],
)
for x, i in expenses:
    print('a:{} b:{}'.format(x, i))




结果:
a:Rent b:1000
a:Gas b:100
a:Food b:300
a:Gym b:50
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表