02python程序设计基础——字符串

字符串方法 format

1.替换字段名

在最简单的情况下,只需向 format 提供要设置其格式的未命名参数,并在格式字符串中使用未命名字段。此时,将按顺序将字段和参数配对。你还可给参数指定名称,这种参数将被用于相应的替换字段中。你可混合使用这两种方法。

In [2]:
"{foo} {} {bar} {}".format(1, 2, bar=4, foo=3)
Out[2]:
'3 1 4 2'
 

还可通过索引来指定要在哪个字段中使用相应的未命名参数,这样可不按顺序使用未命名 参数。

In [3]:
"{foo} {1} {bar} {0}".format(1, 2, bar=4, foo=3)
Out[3]:
'3 2 4 1'
 

2.基本转换

指定要在字段中包含的值后,就可添加有关如何设置其格式的指令了。首先,可以提供一个 转换标志。

In [4]:
print("{pi!s} {pi!r} {pi!a}".format(pi="π"))
 
π 'π' '\u03c0'
 

上述三个标志( s 、 r 和 a )指定分别使用 str 、 repr 和 ascii 进行转换。函数 str 通常创建外观 普通的字符串版本(这里没有对输入字符串做任何处理)。函数 repr 尝试创建给定值的Python表 示(这里是一个字符串字面量)。函数 ascii 创建只包含ASCII字符的表示

 

你还可指定要转换的值是哪种类型,更准确地说,是要将其视为哪种类型。例如,你可能提 供一个整数,但将其作为小数进行处理。为此可在格式说明(即冒号后面)使用字符 f (表示定 点数)。

In [5]:
"The number is {num}".format(num=42)
Out[5]:
'The number is 42'
In [6]:
"The number is {num:f}".format(num=42)
Out[6]:
'The number is 42.000000'
 

你也可以将其作为二进制数进行处理。

In [7]:
"The number is {num:b}".format(num=42)
Out[7]:
'The number is 101010'

3.宽度、精度和千位分隔符

宽度是使用整数指定的,如下所示:

In [8]:
"{num:10}".format(num=3)
Out[8]:
'         3'
In [9]:
"{name:10}".format(name="Bob")
Out[9]:
'Bob       '
 

如你所见,数和字符串的对齐方式不同。对齐将在下一节介绍。

 

精度也是使用整数指定的,但需要在它前面加上一个表示小数点的句点。

In [11]:
"Pi day is {pi:.2f}".format(pi=3.14159)
Out[11]:
'Pi day is 3.14'
 

当然,可同时指定宽度和精度。

In [13]:
"{pi:10.2f}".format(pi=3.14159)
Out[13]:
'      3.14'
 

实际上,对于其他类型也可指定精度,但是这样做的情形不太常见。

In [14]:
"{:.5}".format("Guido van Rossum")
Out[14]:
'Guido'
 

最后,可使用逗号来指出你要添加千位分隔符。

In [15]:
'One googol is {:,}'.format(10 ** 100)
Out[15]:
'One googol is 10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000'
 

4.符号、对齐和用 0 填充

有很多用于设置数字格式的机制,比如便于打印整齐的表格。在大多数情况下,只需指定宽 度和精度,但包含负数后,原本漂亮的输出可能不再漂亮。另外,正如你已看到的,字符串和数 的默认对齐方式不同。在一栏中同时包含字符串和数时,你可能想修改默认对齐方式。在指定宽 度和精度的数前面,可添加一个标志。这个标志可以是零、加号、减号或空格,其中零表示使用 0来填充数字。

In [17]:
'{:010.2f}'.format(3.14159)
Out[17]:
'0000003.14'
 

要指定左对齐、右对齐和居中,可分别使用 < 、 > 和 ^ 。

In [18]:
print('{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}'.format(3.14159))
 
3.14      
   3.14   
      3.14
 

可以使用填充字符来扩充对齐说明符,这样将使用指定的字符而不是默认的空格来填充。

In [4]:
"{:$^15}".format(" WIN BIG ")
Out[4]:
'$$$ WIN BIG $$$'
 

字符串格式设置示例

In [6]:
# Print a formatted price list with a given width

width = 35
# width = int(input('Please enter width: '))

price_width = 10
item_width = width - price_width

header_fmt = '{{:{}}}{{:>{}}}'.format(item_width, price_width)
fmt = '{{:{}}}{{:>{}.2f}}'.format(item_width, price_width)

print('=' * width)

print(header_fmt.format('Item', 'Price'))

print('-' * width)

print(fmt.format('Apples', 0.4))
print(fmt.format('Pears', 0.5))
print(fmt.format('Cantaloupes', 1.92))
print(fmt.format('Dried Apricots (16 oz.)', 8))
print(fmt.format('Prunes (4 lbs.)', 12))

print('=' * width)
 
===================================
Item                          Price
-----------------------------------
Apples                         0.40
Pears                          0.50
Cantaloupes                    1.92
Dried Apricots (16 oz.)        8.00
Prunes (4 lbs.)               12.00
===================================
 

字符串方法

1. center

方法 center 通过在两边添加填充字符(默认为空格)让字符串居中。

In [8]:
"The Middle by Jimmy Eat World".center(39)
Out[8]:
'     The Middle by Jimmy Eat World     '
In [9]:
"The Middle by Jimmy Eat World".center(39, "*")
Out[9]:
'*****The Middle by Jimmy Eat World*****'
 

2.find

方法find在字符串中查找子串。如果找到,就返回子串的第一个字符的索引,否则返回 - 1 。

In [11]:
'With a moo-moo here, and a moo-moo there'.find('moo')
Out[11]:
7
In [12]:
title = "Monty Python's Flying Circus"
title.find('Monty')
Out[12]:
0
In [13]:
title.find('Python')
Out[13]:
6
In [14]:
title.find('Zirquss')
Out[14]:
-1
In [16]:
subject = '$$$ Get rich now!!! $$$'
subject.find('$$$')
Out[16]:
0
In [17]:
subject.find('$$$', 1)  # 只指定了起点
Out[17]:
20
In [18]:
subject.find('!!!', 0, 16)  # 同时指定了起点和终点
Out[18]:
-1
 

3.join

join 是一个非常重要的字符串方法,其作用与 split 相反,用于合并序列的元素。

In [19]:
seq = [1, 2, 3, 4, 5]
ep = '+'
sep.join(seq)  # 尝试合并一个数字列表
 
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-19-f3b632463406> in <module>
      1 seq = [1, 2, 3, 4, 5]
      2 ep = '+'
----> 3sep.join(seq)  # 尝试合并一个数字列表

NameError: name 'sep' is not defined
In [20]:
seq = ['1', '2', '3', '4', '5']
ep.join(seq)  # 合并一个字符串列表
Out[20]:
'1+2+3+4+5'
 

4.lower

方法 lower 返回字符串的小写版本。

In [21]:
'Trondheim Hammer Dance'.lower()
Out[21]:
'trondheim hammer dance'
 

5.replace

方法 replace 将指定子串都替换为另一个字符串,并返回替换后的结果。

In [22]:
'This is a test'.replace('is', 'eez')
Out[22]:
'Theez eez a test'
 

6.split

split 是一个非常重要的字符串方法,其作用与 join 相反,用于将字符串拆分为序列。

In [23]:
'1+2+3+4+5'.split('+')
Out[23]:
['1', '2', '3', '4', '5']
 

7.strip

方法 strip 将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果。

In [25]:
' internal whitespace is kept '.strip()
Out[25]:
'internal whitespace is kept'

猜你喜欢

转载自www.cnblogs.com/xinmomoyan/p/10797819.html
今日推荐