20170721_python字符串操作_《python语言及其应用》

str = 'abcde...wxyz'

[num]提取指定字符

str[0] == 'a'

str[1] == 'b'

str[-1] == 'z'

 

[start:end:step]分片/切片,一定要带上:冒号.end是偏移量,偏移位数,偏移到的key=偏移位数-1

str[:] == str[0:] ==str[0:-1] == str[0:26] == str #取所有元素

str[:10] == str[0:10] = 'abcdefghi'  #从0开始取10位,也就是 str[0]到str[9]

str[23:] == str[-3:] == 'xyz' #从str[23]开始取到最后 == 从倒数第三位取到最后

str[19::4] == 'tx' #从str[19]开始每隔4位取1次

str[:21:5] =='afkpu' #从第一位开始取到21位,每隔5位取1次

str[::7] == 'ahov' #从0开始到最后,每隔7位取1次

str[-1::-1] == str[::-1] == 'zyxw...cba' #从最后一位取到第一位,每隔-1位取一次

切片start:小于起始位置的偏移量被当做0,也就是起始位置,end:大于终止位置的偏移量被当做-1

end可以理解为

①提取到str[end]的前一位,也就是str[end-1]位,

②也可以理解为提取到end位,由于是从0开始,那么第end位为str[end-1] (自己的理解,应该没错)

 

split()分割/提取?以指定字符为分隔符,把字符串分割为由若干子串组成的列表list.

str = 'abc , def , higkl,mn opq'

str.split(',') == ['abc', 'def', 'higkl', 'mn opq'] #以,为分隔符,组成list

str.split() == ['abc', ',', 'higkl,mn', 'opq'] #如果没有指定分隔符,则默认为空格或换行

 

join()列表合并字符串

strList = ['A', 'B', 'C', 'D']

str = ','.join(strList) #str = 'A,B,C,D',把列表的元素取出来,以','逗号为分隔符连接起来

 

字符串查找

str = '''Today, my friends and I decided to take a visit to an old town which was near our city.

We had heard of it for a long time, but we never had the chance to go there.

A week ago, I happened to read an article about the old town'''

str.startswith('Today') == True #是不是以'Today'开头,这里区分大小写

str.endswith('there.') == True #是不是以'there.'结尾

str.find('we') #查找第一次出现'we'的位置(偏移量)

str.rfind('we') #查找最后一次出现'we'的位置(偏移量)

str.count('we') #查找'we'出现的次数

str.isalnum() == False #所有的字符都是数字或者字母

 

字符串删除和格式化(如大小写)

str = ' my friends and ...'

str.strip('.') == 'my friends and' #删除所有'.'字符

str.capitalize() == 'My friends and' #首字母大写

str.title() == 'My Friends And' #所有单词首字母大写

str.upper() str.lower() #所有字母大写/小写

str.swapcase() #所有字母大小写转换

str.center(30) == '      my friends and ...      ' #在30个字符位居中显示

str.ljust(30) str.rjust(30) #同上 居左 居右显示

 

replace()字符串替换,参数:需要被替换的子串,用于替换的新子串,需要替换多少次(为空则默认只替换第一个)

str = 'AA, ABab '

str.replace('A','AA')  ==  'AAA, ABab' #只替换第一个

str.replace('A','AA',3) == 'AAAA,AABab'#替换3次

 

以上的字符串操作都没有改变字符串,在python中字符串是不可变的,应该是在内存中创建了一个字符串,这个字符串无法被改变

上面的操作只是在内存中建立了一个新的字符串,可以指向一个新建的变量来保存他

如str = 'abc' str += 'def'

①新建abc字符串

②新建str变量

③str指向abc,或者是str引用了abc?

④新建一个字符串 abcdef 

⑤abcdef指向str

⑥abc没有被引用或者指向,然后就被回收了?

 

posted @ 2017-07-21 16:42  emmmmmm1  阅读(228)  评论(0编辑  收藏  举报