4

python第三节:Str字符串类型(2)

 8 months ago
source link: https://blog.51cto.com/u_16427934/9187021
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

python第三节:Str字符串类型(2)

精选 原创

str.format(*args, **kwargs)

执行字符串格式化操作。

语法:点号前面是一个带槽(由大括号表示)的字符串,字符串里面可以设置各种参数和格式控制标记,后面是format和替换的字符串。

{参数序号:格式控制标记}

如下六个按照顺序使用。

用于填充的单个字符

<左对齐

>右对齐

槽的设定输入宽度

数字的千分位分隔符,适用于整数和浮点数

浮点数小数部分精度或字符串最大输出长度

c整数对应的unicode字符 d 十进制

x十六进制小写

X十六进制大写

浮点数类型

e浮点数对应的小写字母e的形式

E浮点数对应的大写字母E的形式

f标准浮点数

%浮点数的百分比形式

str1 = "{}是一个{}".format('这','苹果')

print(str1)

str1 = "{1}是一个{0}".format('这','苹果')  # 指定位置

print(str1)

person = {"name":'mike',"age":12}

print("{name} is {age} years old!".format(**person))  # 字典拆包

print("{age} is {name} years old!".format(**person))



s0 = "测试测试"

s1 = "$"

s2 = 3

print("{:25}".format(s0))  # 宽度一共25,后面默认填充空格

print("{0:+^25}".format(s0))  # 居中,加号填充

print("{0:*>25}".format(s0))  # 右对齐,星号填充

print("{0:{1}^25}","{0:{1}^25}".format(s0,s1))

print("{1:{1}^25}","{1:{1}^25}".format(s0,s1))

print("{:_^25,}".format(234567890))  # 千分位分隔符

print("{:>25.2f}".format(3.1415926))

print("{:s}".format("1234师打发士大夫撒旦法师的"))

print("{0:b},{0:c},{0:d},{0:o},{0:x},{0:X}".format(289))

print("{0:e},{0:E},{0:f},{0:%}".format(3.1415))

结果:

这是一个苹果

苹果是一个这

mike is 12 years old!

12 is mike years old!

++++++++++测试测试+++++++++++

*********************测试测试

{0:{1}^25} $$$$$$$$$$测试测试$$$$$$$$$$$

{1:{1}^25} $$$$$$$$$$$$$$$$$$$$$$$$$

_______234,567,890_______

1234师打发士大夫撒旦法师的

100100001,ġ,289,441,121,121

3.141500e+00,3.141500E+00,3.141500,314.150000%

str.format_map(mapping)

类似于str.format(**mapping),不同之处在于mapping会被直接使用而不是复制到一个  dict。 此方法常用场景是当mapping为 dict 的子类的情况:

class Default(dict):

    def __missing__(self, key):

        print(key)

        return key



print('{name} was born in {country}'.format_map(Default(name='Guido')))

print('{name} was born in {country}'.format_map({'name':'Guido','country':'RUSSIA'}))

country

Guido was born in country

Guido was born in RUSSIA

上面例子中,一共两个key是name和country,第一个是country这个key确实,自动填充为country。

  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK