python对于字符串的操作确实是十分便利,find()、partition()、split()、strip()这些就不说了,在这里说些其他有意思且十分快捷便利的操作。

1、转换大小写

除了upper、lower之外,Python还有capitalize()、title()、swapcase(),分别是将字符串首字母变为大写、将每个单词的首字母变为大写以及大小写互换。

>>> s="What is Your Name?"
>>> s2=s.lower()
>>> s2.capitalize()
"What is your, name?"
>>> s.title()
'What Is Your Name?'
>>> s.swapcase()
'wHAT IS yOUR nAME?'

2、映射转换函数maketrans和translate

这两个函数一起确实是非常方便了,可以将字符串的一些字母按一一对应关系转换(所以字符数目要相同)。但在Python2和Python3中略有不同

  • Python2(需要import string,string.maketrans())
>>> import string
>>> table=string.maketrans("abcdef123","uvwxyz@#$")
>>> s="Python is a great programming language. I like it!"
>>> s.translate(table)
"Python is u gryut progrumming lunguugy. I liky it!"
>>> s.translate(table,"gtm")  # 第二个参数表示要删除的字符
"Pyhon is u ryu proruin lunuuy. I liky i!"
  • Python3(不需要import,直接str.maketrans()或byte.maketrans())
>>> table=str.maketrans('abcdef123','uvwxyz@#$')
>>> s='Python is a great programming language. I like it!'
>>> s.translate(table)
'Python is u gryut progrumming lunguugy. I liky it!'
>>> s.translate(table,'gtm')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: translate() takes exactly one argument (2 given)

可以发现,在Python2中translate函数可以有第二个参数表示要删除的字符,但是在Python3中只允许有一个参数,事实上, 是Python3的str.translate只能有一个参数,但byte.translate仍然可以有两个。

3、字符串常量

随机密码生成就是基于字符串常量。

(random.choice是从一个序列中随机取出一个元素,s.join(x)是用字符串s连接x)

>>> import string
>>> x = string.digits + string.ascii_letters + string.punctuation
>>> x
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> import random
>>> ''.join([random.choice(x) for i in range(8)])
'H\\{.#=)g'

4、可变字符串

我们都知道,在python中元组和字符串都属于不可变序列。但如果确实需要一个支持原地修改的unicode数据对象,可以使用io.StringIO对象或array模块。

  • StringIO

StringIO用于读写字符串缓冲,可以用字符串初始化(一般用unicode)。可以使我们像读写文件一样读写字符串。其中的seek方法从字面上难以理解,下面是官方文档。

python提取首字母 python提取短语首字母大写_字符串

简单来说,就是将指针相对于whence的移动offset个位置,whence默认为0(即指向第一个),返回值为现所指位置。

>>> import io
>>> s=u'hello, world'
>>> sio=io.StringIO(s)
>>> sio.getvalue()    //得缓冲字符串的全部内容
'hello, world'
>>> sio.seek(7)      //文件指针指向7
7
>>> sio.write('there!')    //在所指位置写入,返回的是写入长度
6
>>> sio.getvalue()
'hello, there!'
>>> sio.read()
''
>>> sio.seek(0)
0
>>> sio.read()
'hello, there!'

可以发现使用seek函数即指向第7个位置,即指向‘w’,在次写入'there!'替换原来的元素。此时若再调用read函数,即无可读内容,这也很容易理解,因为就像文件一样,write()后文件指针指向末尾了,我们需要调用seek函数再重新指向开头,便可读出全部内容。

  • array

python提取首字母 python提取短语首字母大写_Python_02

常用typecode:

'u'    Unicode character

'i'     int

'f'     float                 
'd'    float

>>> import array
>>> a=array.array('u',u'Hello, world')
>>> a
array('u', 'Hello, world')
>>> a[0]=u'y'
>>> a
array('u', 'yello, world')
>>> a.tounicode()
'yello, world'