Python 从入门到放弃(二)

来源:互联网 发布:公司网站数据库在哪里 编辑:程序博客网 时间:2024/05/22 06:21

Python 从入门到放弃(二)

2011/12/06 Wed 09:51

字符串

字符串都是不可变的,分片赋值不合法:

mystr = 'cogito, ergo sum'mystr[1:5] = 'abcd'Traceback (most recent call last):  File "<ipython-input-5-d83c7aa5ecd5>", line 1, in <module>    mystr[1:5] = 'abcd'TypeError: 'str' object does not support item assignment

字符串格式化方法:百分号(%)实现,多个时用tuple实现,如:

format = 'sakura when i see it hit the %s my %s gets weak'formatOut[7]: 'sakura when i see it hit the %s my %s gets weak'values = ('ground','heart')valuesOut[9]: ('ground', 'heart')format % valuesOut[10]: 'sakura when i see it hit the ground my heart gets weak'

在python中只有tuple和dict可以格式化多个值,而list等序列会被解释为一个值。
可以在格式化时提供精度和格式,如下:

format = 'print a number in format: %10.3f' % 3.14159265formatOut[12]: 'print a number in format:      3.142'format = 'print a number in format: %-10.3f' % 3.14159265formatOut[14]: 'print a number in format: 3.142     'format = 'print a number in format: %+10.3f' % 3.14159265formatOut[16]: 'print a number in format:     +3.142'format = 'print a number in format: %010.3f' % 3.14159265formatOut[18]: 'print a number in format: 000003.142'

10.3f 中 f 为类型,10为最小宽度,3为小鼠精度,- 表示左对齐,+ 表示显示正负号,0 表示如不够宽度则用0补全,不表示八进制。
ps:python中0和0x表示八进制数和十六进制数,如

010Out[2]: 80x10Out[3]: 16

字符串转换类型除了 f 还有

d :signed int (dec)
o :unsigned (oct)
u :unsigned dec
x / X : unsigned hex
e / E :科学计数法
s : 用str转换任意python对象
r : 用repr转任意python对象

如果用×作为宽度或者精度,则从tuple参数中读取,如:

format = 'print a number in format: %*.3f' % (15,3.14159265)formatOut[22]: 'print a number in format:           3.142'format = 'print a number in format: %*.*f' % (15,5,3.14159265)formatOut[24]: 'print a number in format:         3.14159'format = 'print a number in format: %10.*f' % (5,3.14159265)formatOut[26]: 'print a number in format:    3.14159'

字符串方法:

  1. find : 查找子串,返回左索引,找不到返回 -1 ,后面的参数指定起止点,左闭右开。注意,返回零表示在开头找到,不是boolean。

    mystrOut[27]: 'cogito, ergo sum'mystr.find('co')Out[28]: 0mystr.find('er')Out[29]: 8mystr.find('er',1,5)Out[30]: -1
  2. join :用某符号连接,是split的逆过程。

    dirs = ['.','mycode','cnn','denoise']dirsOut[32]: ['.', 'mycode', 'cnn', 'denoise']'/'.join(dirs)Out[33]: './mycode/cnn/denoise' 
  3. lower :返回小写。

  4. replace :替换,后项参数替换掉前面的参数。

  5. split :分割,如果没有分割符号,则用所有空格,制表,回车分割。

    mydirOut[35]: './mycode/cnn/denoise'mydir.split('/')Out[36]: ['.', 'mycode', 'cnn', 'denoise']
  6. translate :把ASCII 字符集中的某些值替换成另一值,相当于重新生成了一个表之间的映射,maketrans 生成的 table 即为一个新的 ASCII 表。

    from string import maketranstable = maketrans('aeiou','mnbpt')'das ist ein auto'.translate(table)Out[39]: 'dms bst nbn mttp'

以上整理字符串相关的常用内容。

THE END

reference:
1. 《Python基础教程》([挪] Magnus Lie Hetland 著)

原创粉丝点击