Python 学习笔记(1)——字符串的处理

来源:互联网 发布:网络空间安全战略 编辑:程序博客网 时间:2024/06/01 22:29

一、字符串

1.  split()函数

基于分隔符将字符串分割成有若干子字符串组成的列表。例如:

string="a b c,d e f,g"string.split()Out[4]:  ['a', 'b', 'c,d', 'e', 'f,g']</span>

2. join() 函数

它将若干子串的列表分解,并将这些子字符串合成一个完整的大的字符串。 例如

slist=['a','cd','f']
string=','.join(slist) #中间用逗号隔开
print(string)Out[6]: a,cd,f
startwith('A') #字符串是否是以“A”开头,返回True/False
endwith('A')   #字符串是否是以“A”结尾,返回True/False
find('A')      #字符串中“A”的位置,返回偏移量</span>
count('A')     #字符串中"A"出现的次数</span>
isalnum()      #字符串中所有字符都是数字或者字母,返回True/False</span>

strip()函数,删去字符串尾部的字符,若无指定字符,默认删去换行符\n,例如:

##字符串是不可改变的,下面这些案列没有真正的将字符串改变,而只是获取字符串的值并赋值给了新的字符串。使得看起来结果发生了变化一样

string="this is a big data..." 
string.strip() 
Out[9]: 'this is a big data...' 
string.strip('.') 
Out[10]: 'this is a big data'
5.string.capitalize()  #将首字母大写Out[11]: 'This is a big data...' ##字符串并未改变
string.title()       #将所有首字母大写Out[13]: 'This Is A Big Data...'
string.lower()       #将所有字符变成小写Out[14]: 'this is a big data...'  string.upper()       #将所有字符变成大写Out[15]: 'THIS IS A BIG DATA...'
string='This is A big data...'</span>
  string.swapcase()     #将所有大小写转换Out[18]: 'tHIS IS a BIG DATA...'
len(string)    #字符串的长度Out[19]: 21
6. 其他字符串的处理:
str(95)  #强制类型Out[20]: '95'  print('\tabc')  #‘\’转义字符        abc

7.  使用 [start:end:step] 分片:

[ : ] 提取从开头到结尾的整个字符串

[start:] 从start到结尾

[: end] 从开头到end-1

[start:end] 从start 到end-1

[start:end:step] 从start到end-1, step为步长

For example:

stringOut[22]: 'This is A big data...'  string[1:]Out[23]: 'his is A big data...'
string[5:20:5]Out[25]: 'iba'





0 0
原创粉丝点击