Python学习-第三章 字符串

使用字符串

字符串是不可变的,因此所有元素赋值和切片赋值都是非法的。

>>> format="Hello,%s.%s enough for ya?"
>>> values=('world','Hot')
>>> format%values
'Hello,world.Hot enough for ya?'

上述格式字符串中的%s称为转换说明符,指出了要将值插入在什么地方。s意味着将值视为字符串进行格式设置。如果指定的值不是字符串,将使用str将其转换为字符串。

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('Apple',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)

在这里插入图片描述

  1. string.digits:包含数字0~9的字符串
  2. string.ascii_letters:包含所有ASCII字母(大写和小写)的字符串
  3. string.ascii_lowercase:包含所有小写ASCII字母的字符串
  4. string.printable:包含所有可打印的ASCII字符的字符串
  5. string.puntuation:包含所有ASCII标点字符的字符串
  6. string.ascii_uppercase:包含所有大写ASCII字母的字符串
    方法center通过在两边填充字符(默认为空格)让字符串居中
>>> "The Middle by Jimmy Eat World".center(39)
'     The Middle by Jimmy Eat World     '
>>> "The Middle by Jimmy Eat World".center(39,"*")
'*****The Middle by Jimmy Eat World*****'

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

>>> 'With a moo-here,and a moo-moo there'.find('moo')
7
>>> title="Monty Python's Flying Circus"
>>> title.find('zirquss')
-1

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

>>> seq=['1','2','3','4','5']
>>> sep='+'
>>> sep.join(seq)
'1+2+3+4+5'
>>> dirs='','usr','bin','env'
>>> '/'.join(dirs)
'/usr/bin/env'

方法lower返回字符串的小写版本。
方法title是将字符串转换为词首大写,即所有单词的首字母都大写,其他字母都小写。然而,它确定单词边界的方式可能导致结果不合理。

>>> "that's all folks".title()
"That'S All Folks"

另一种方法是使用模块string中的函数capwords。

>>> import string
>>> string.capwords("that's all,folks")
"That's All,folks"

方法replace将制定子串都替换为另一个字符串,并返回替换后的结果。
方法split用于将字符串拆分为序列。

>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']

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

>>> '    internal whitespace is kept    '.strip()
'internal whitespace is kept'

方法translate与replace一样替换字符串的特定部分,但不同的是它只能进行单字符替换。使用translate前必须创建一个转换表。要创建转换表,可对字符串类型str调用方法maketurns,这个方法接受两个参数:两个长度相同的字符串。调用方法maketurns还可以提供可选的第三个参数,指定要将哪些字母删除。

猜你喜欢

转载自blog.csdn.net/weixin_43340018/article/details/83050489