python学习笔记:字符串

string类型由多个字符组成,可以把字符串看成一个整体,也可以取得字符串中的任何一个部分。

函数len() 返回字符串的长度

>>> address = 'www.baidu.com'
>>> len(address)
13
View Code

用for语句遍历字符串

从第一个字符开始,按照顺序读取字符,然后在做相应的处理,直到最后一个字符,这个处理过程我们称为遍历。

>>> for char in address :
...     print char
View Code

字符串片断

字符串的一部分叫做片断,操作符 [n:m] 返回字符串的一部分,从第n个字符开始到第m个字符结束,包括第n个,但是不包括第m个。只写m表示从索引0开始,只写n表示从n到最后一个字符。

>>> os = "linux unix freeBSD"
>>> print os[0:5]
linux
>>> print os[6:10]
unix
>>> print os[:5]
linux
>>> print os[11:]
freeBSD
View Code

我们知道字符串是不可变的,如果我们修改其中的一个字符,最好的操作就是取字符串的一部分和添加或更换的字符串相加,形成一个新的字符串:

>>> s = "use Python!"
>>> new_s = s[0:3]+" p"+s[5:]
>>> print new_s
use python!
View Code

如果仅仅只是替换一个子字符串的话,可以用字符串的replace()方法来实现:

>>> S = "spammy"
>>> S = S.replace('mm','xx')
>>> print S
spaxxy
View Code

字符串模块

字符串模块string包含一些处理字符串的函数。在用到模块前必须先引入:import string

字符串模块中包含一个名为find的查找字符的函数:

>>> yourname = "your name is limingming"
>>> import string
>>> index = string.find(yourname,"m")
>>> print index
7
View Code

 程序中常常需要判断字符是大写还是小写,或者判断是字符还是数字。string模块中提供了几个比较有用的常量字符串

所有的小写字母string.lowercase  所有的大写字母string.uppercase  从0到9的数字string.digits

>>> import string
>>> print string.lowercase
abcdefghijklmnopqrstuvwxyz
>>> print string.uppercase
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> print string.digits
0123456789
View Code

我们可以利用这几个常量字符串,编写一个是否为小写的函数

import string
def isLowercase(char):
    return  string.find(string.lowercase,char)  !=  -1
View Code
import string
def isLowercase(char):
    return char in string.lowercase
View Code
import string
def isLowercase(char):
    return 'a' <= char <='z'
View Code

相关推荐