python基础笔记--使用字符串

1. 字符串格式化

%左侧放置格式化的字符串,右侧放置希望格式化的值。格式化的值可以使用元组来表示。不能使用元组或者其他序列代替元组,可以使用元组和字典格式化一个以上的值。

1 >>> format = "Hello. %s %s enough for ya?"
2 >>> values = ('world', 'Hot')
3 >>> print format % values
4 Hello. world Hot enough for ya?

模板字符串

 1 说明:模板方法substitute会用传递进来的关键字参数foo_value替换字符串中的$foo
 2 >>> from string import Template
 3 >>> s = Template('$x, glorious $x!')
 4 >>> s.substitute(x='slum')
 5 'slum, glorious slum!'
 6 说明:使用${x}替换单词的一部分
 7 >>> s = Template("It's ${x}tastic!")
 8 >>> s.substitute(x='slum')
 9 "It's slumtastic!"
10 说明:$$写出$符号
11 >>> s = Template("Make $$ selling $x!")
12 >>> s.substitute(x='slum')
13 'Make $ selling slum!'
14 说明:使用字典提供值/名称对
15 >>> s = Template('A $thing must never $action.')
16 >>> d = {}
17 >>> d['thing'] = 'gentleman'
18 >>> d['action'] = 'show his socks'
19 >>> s.substitute(d)
20 'A gentleman must never show his socks.'

转换说明符:(1)-表示左对齐,+表示在转换值之前要加上正负号,“ ”空白字符表示正数之前保留空格,0表示转换值若位数不够则用0填充。(2)点(.)后跟精度值可选,如果是实数,表示小数点后的位数,如果是字符串,表示最大字段宽度。(3) %*s 可以从用户输入得到字符宽度。

#-*- coding: utf-8 -*-

width = input('Please enter  ')
price_width = 10
item_width = width - price_width
header_format = '%-*s%*s'
format1 = '%-*s%*.2f'

print '=' * width
print header_format % (item_width, 'Item', price_width, 'Price')

print '-' * width
#%*s从item_width中读取字符宽度
print format1 % (item_width, 'Apples', price_width, 0.4)
print format1 % (item_width, 'Pears', price_width, 0.5)
print format1 % (item_width, 'Cantaloupes', price_width, 1.92)
print format1 % (item_width, 'Dried Apricots(16 oz)', price_width, 8)
print format1 % (item_width, 'Prunes (4 lbs)', price_width, 12)

结果:
=================== RESTART: E:/02_PyhonCode/strformat.py ===================
Please enter  50
==================================================
Item                                         Price
--------------------------------------------------
Apples                                        0.40
Pears                                         0.50
Cantaloupes                                   1.92
Dried Apricots(16 oz)                         8.00
Prunes (4 lbs)                               12.00

2. 字符串方法

字符串常量:

1 string.digits: 包含数字0-9的字符串
2 string.letters: 包含所有字母(大写或小写)的字符串
3 string.lowercase: 包含所有小写字母的字符串
4 string.printable: 包含所有可打印字符串
5 string.punctuation: 包含作呕标点
6 string.uppercase: 包含所有大写字母

2.1  find方法可以在一个较长的字符串中查找子字符串。返回子串坐在位置的最左端索引,如果没有找到则返回-1。

 1 >>> title = "Monty Python's Flying Circus"
 2 >>> title.find('Monty')
 3 0
 4 >>> title.find('t')
 5 3
 6 >>> title.find("Zipo")
 7 -1
 8 >>> subject = '$$$ Get rich now!!! $$$'
 9 >>> subject.find('$$')
10 0
11 # 提供查找的开始位置
12 >>> subject.find('$$', 3)
13 20
14 # 提供查找字符串的开始到结尾的索引
15 >>> subject.find('!!!', 0, 10)
16 -1
17 >>> subject.find('!!!', 0, 16)
18 -1
19 >>> subject.find('!!!', 0, 20)
20 16 

2.2  join方法,是split方法的你方法,用来在队列中添加元素。队列元素必须是字符串。

 1 >>> seq = [1, 2, 3, 4, 5]
 2 >>> sep = '+'
 3 >>> sep.join(seq) #链接数字列表
 4 
 5 Traceback (most recent call last):
 6   File "<pyshell#146>", line 1, in <module>
 7     sep.join(seq) #链接数字列表
 8 TypeError: sequence item 0: expected string, int found
 9 >>> seq = ['1', '2', '3', '4', '5']
10 >>> sep.join(seq)
11 '1+2+3+4+5'
12 >>> dirs = ' ', 'usr', 'bin', 'env'
13 >>> '/'.join(dirs)
14 ' /usr/bin/env'
15 >>> dirs = '', 'usr', 'bin', 'env'
16 >>> '/'.join(dirs)
17 '/usr/bin/env'
18 >>> print 'C:'+'\'.join(dirs)
19 C:usrinenv

2.3  lower方法返回字符串的小写字母版

>>> 'Trondheim Hammer Dance'.lower()
'trondheim hammer dance'
>>> name = 'Gumby'
>>> names = ['gumby', 'smith', 'jones']
>>> if name.lower() in names:
    print 'Found it!'

    
Found it!
>>>

标题转换,将单词的首字母大写。

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

2.4  replace对象,返回某字符串的所有匹配项均被替换之后得到字符串。

>>> 'This is a test'.replace('is', 'eez')
'Theez eez a test'

2.5  split方法

>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
>>> 'Using the default'.split()
['Using', 'the', 'default']

2.6  strip方法

 1 >>> '    internal whitespace is kept   
'.strip()
 2 'internal whitespace is kept'
 3 >>> names = ['gumby', 'smith', 'jones']
 4 >>> name = 'gumby'
 5 >>> if name in names:
 6     print 'Found it!'
 7 
 8     
 9 Found it!
10 >>> if name.strip() in names:
11     print 'Found it!'
12 
13     
14 Found it!
15 >>> '*** SPAM * for * everyone!!! ***'.strip(' *!')
16 'SPAM * for * everyone'
17 >>> 

2.7  translate方法

translate方法和replace方法一样,可以替换字符串中的某些部分,但是不同之处在于translate方法只处理单个字符。优势在于可以同时进行多个替换。

举例:把英文文本转换为德文。使用translate转换之前,需要完成一张转换表。使用string模块中的maketrans函数完成转换表。maketrans函数接收两个参数:两个等长的字符串,表示第一个字符串中的字符用第二个字符串中相同位置的字符替换。

原文地址:https://www.cnblogs.com/mymindview/p/8372846.html