字符串
字符串是 Python 中最常用的数据类型。我们可以使用引号('或")来创建字符串。
以下是常见的操作
- 增
- 删除
- 改
- 查
字符串常用操作
- 增
In [12]: name = 'caimengzhi' In [13]: name Out[13]: 'caimengzhi'
但是字符串内有单引号的时候请使用双引号""否则报错
In [14]: name = 'let's go' File "<ipython-input-14-f9c5b618a709>", line 1 name = 'let's go' # 因为内部有单引号,外面在使用双引号就报错 ^ SyntaxError: invalid syntax In [15]: name = "let's go" In [16]: name Out[16]: "let's go"
- 删除
In [17]: name = 'caimengzhi' In [18]: del name # del是全局,不但适用了字符串,列表,字典等等 In [19]: name --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-19-18697449d7c4> in <module>() ----> 1 name NameError: name 'name' is not defined
- 改
In [23]: name = 'caimengzhi' In [24]: name.replace("c","C") Out[24]: 'Caimengzhi'
- 查
切片操作
Python的切片操作,常常还会使用到分割切片,即在[]里使用冒号( : ) 来对字符串进行分割,切片截取是python中字符串常见的一些操作,切片截取的作用是获取子字符或子字符串。实际上,我们要做的就是使用索引,用冒号分隔两个索引,形式为:变量[头下标:尾下标],冒号之前的数字表示开始的位置,冒号之后的数字表示结束的位置。这是一个左闭右开区间,也就是说这个字符串包含头下标,但是不包含尾下标。
Python的数据有两种索引方式:最左边以0开始,依次增加;最右边的元素索引为-1,往左依次减少。
Python的索引很灵活,可以根据具体情况来选择相应的索引方式。
切片索引,也就是字符串中字符的下标。从0开始计算
切片的使用语法是:字符串变量名[x:y],表示下标从x到y的一段字符串(不包括y)。当x不写为,像[:y],表示从头开始,相当于[0:y]。当y不写时,表示一直到尾。当x和y两个都不写时,就表示整个字符串。
1. 全部选中
In [1]: name = 'caimengzhi' In [2]: name Out[2]: 'caimengzhi'
2. 选择其中部分
In [4]: name[0:3] # 0表示开始,3表示结束,典型的顾头不顾尾。 Out[4]: 'cai'
3. 带步长的选择
In [5]: name = 'caimengzhi' In [6]: len(name) Out[6]: 10 In [7]: name[0:16:3] # 0表示开始 16表示结束,3表示步长,也就是隔几个选择, Out[7]: 'cmgi'
4. 倒数几位
In [11]: name[-1] # 倒数最后一位 Out[11]: 'i' In [12]: name[-2] # 倒数最第二位 Out[12]: 'h' In [13]: name[-3:] # 倒数最第三位到最后 Out[13]: 'zhi'
字符串常见内置函数操作
1. capitalize 首字母大写
capitalize(...)
S.capitalize() -> string
Return a copy of the string S with only its first character
capitalized.
In [2]: name.capitalize() Out[2]: 'Hello caimengzhi'
2. center 居中显示
center(...)
S.center(width[, fillchar]) -> string
Return S centered in a string of length width. Padding is
done using the specified fill character (default is a space)
In [11]: name.center(50, "-") Out[11]: '-----------------hello caimengzhi-----------------' In [12]: name.center(10,"-") # 要是填空的长度小于本身字符串长度就没有效果 Out[12]: 'hello caimengzhi'
3. count 计算个数
count(...)
S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are interpreted
as in slice notation.
若是没有指出开始和结束就以全部计算
In [13]: name.count("i") # 计算字符c在“caimengzhi”中出现次数 Out[13]: 2 In [18]: name.count("kkk") # 若是没有则返回0 Out[18]: 0
4. endwith 是否以***为结尾,返回True或者False
endswith(...)
S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
(END)
若是没有指出开始和结束就以全部计算
In [21]: name.endswith("kk") # 是否以kk结尾 Out[21]: False In [22]: name.endswith("zhi") # 是否以zhi结尾 Out[22]: True In [40]: name Out[40]: 'hello caimengzhi' In [41]: name.endswith('i',-3,-1) # 倒数第三到倒数到倒数第一(不包括倒数第一),是否以字符i结尾 Out[41]: False In [42]: name.endswith('i',-3) # 倒数第三到倒数到最后是否以字符i结尾 Out[42]: True
startswith 以xxx开头
In [187]: 'hello caimengzhi'.startswith('h')
Out[187]: True
In [188]: 'hello caimengzhi'.startswith('hello')
Out[188]: True
5. find 查找字符串,返回索引值
find(...)
S.find(sub [,start [,end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
In [45]: name Out[45]: 'hello caimengzhi' In [46]: name.find('e') # 全局查找字符e,从左到有查找,直到查找到第一个e就退出 Out[46]: 1 In [47]: name.find('e',5) # 从索引值是5(包括5)的位置开始到最后,查找e,所以查找到的是第二个e Out[47]: 10
rfind 返回字符串最后一次出现的位置(从右向左查询),如果没有匹配项则返回-1。
语法
rfind()方法语法:
str.rfind(str, beg=0 end=len(string))
参数
- str -- 查找的字符串
- beg -- 开始查找的位置,默认为 0
- end -- 结束查找位置,默认为字符串的长度。
In [198]: str = "this is really a string example....wow!!!"; In [199]: substr = "is"; In [200]: In [200]: print str.rfind(substr); 5 In [201]: print str.rfind(substr, 0, 10); 5 In [202]: print str.rfind(substr, 10, 0); -1 In [203]: print str.find(substr); 2 In [204]: print str.find(substr, 0, 10); 2 In [205]: print str.find(substr, 10, 0); -1
6. format 字符串格式化输出
format(...)
S.format(*args, **kwargs) -> string
Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
它通过{}和:来代替%。
In [54]: "{0}{1}{2}' is good man".format('cai','meng','zhi') Out[54]: "caimengzhi' is good man" In [55]: "my name is {name} and my age is {age}".format(name="caimengzhi",age="30") # 指定特殊位置 Out[55]: 'my name is caimengzhi and my age is 30'
类似
In [60]: "my name is %s, %d years old" %('caimengzhi',25) # 格式化输出 Out[60]: 'my name is caimengzhi, 25 years old'
7. index 返回字符在字符串中的索引值
index(...)
S.index(sub [,start [,end]]) -> int
Like S.find() but raise ValueError when the substring is not found.
没有指定开始和结束就默认全部
In [66]: name Out[66]: 'hello caimengzhi' In [67]: name.index('e') # 从左到右开始找,找到第一个就退出 Out[67]: 1 # 查找第二个e In [93]: name='hello caimengzhi' In [94]: first=name.index('e') In [95]: first Out[95]: 1 In [96]: name=name[first+1:] In [97]: name Out[97]: 'llo caimengzhi' In [98]: second=name.index('e') In [99]: second Out[99]: 8 In [100]: second_index=first+second+1 In [101]: second_index Out[101]: 10
8 . isalnum(...) 检测字符串是否由字母和数字组成。
S.isalnum() -> bool
Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.
如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False
In [104]: 'hello 123'.isalnum() # 有了空格特殊字符 Out[104]: False In [105]: 'hello123'.isalnum() # 只有数字有字母 Out[105]: True In [106]: 'hello 123'.isalnum() # 有了tab键特殊字符 Out[106]: False In [107]: 'hello!@123'.isalnum() #有了!@#特殊字符 Out[107]: False
9. isalpha() 检测字符串是否只由字母组成。
isalpha(...)
S.isalpha() -> bool
Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.
In [109]: 'hello 123'.isalpha() Out[109]: False In [110]: 'hello123'.isalpha() Out[110]: False In [111]: 'hello'.isalpha() # 只有纯字母 Out[111]: True
In [112]: 'Hello'.isalpha() # 只有纯字母 Out[112]: True
10.isdigit 判断字符串是否全部是纯数字
isdigit(...)
S.isdigit() -> bool
Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
In [116]: '123'.isdigit() Out[116]: True In [117]: '123 '.isdigit() Out[117]: False In [118]: '123A'.isdigit() Out[118]: False In [119]: 12.isdigit() # 因为是判断字符串的,所以报错 File "<ipython-input-119-466e80d3838f>", line 1 12.isdigit() ^ SyntaxError: invalid syntax
11.islower 检测字符串是否由小写字母组成
islower(...)
S.islower() -> bool
Return True if all cased characters in S are lowercase and there is
at least one cased character in S, False otherwise.
In [123]: 'aaa'.islower() Out[123]: True In [124]: 'aaaA'.islower() Out[124]: False
12. isspace 检测字符串是否空格(1个以上空格)组成
isspace(...)
S.isspace() -> bool
Return True if all characters in S are whitespace
and there is at least one character in S, False otherwise.
In [126]: 'ca'.isspace() Out[126]: False In [127]: 'ca '.isspace() Out[127]: False In [128]: ''.isspace() Out[128]: False In [129]: ' '.isspace() # 有一个空格 Out[129]: True In [130]: ' '.isspace() # 有多个空格 Out[130]: True
13. istitle 检查字符串是否是标题组成,字母开始大写
istitle(...)
S.istitle() -> bool
Return True if S is a titlecased string and there is at least one
character in S, i.e. uppercase characters may only follow uncased
characters and lowercase characters only cased ones. Return False
otherwise.
In [131]: 'hello caimengzhi'.istitle() Out[131]: False In [132]: 'hello caimengzhi'.istitle() Out[132]: False In [133]: 'Hello Caimengzhi'.istitle() Out[133]: True In [134]: 'Hello caimengzhi'.istitle() Out[134]: False In [136]: 'hello Caimengzhi'.istitle() Out[136]: False # 必须每个单词开始单词开头大学
14. isupper 检查字符串是否是全部大写字母组成
isupper(...)
S.isupper() -> bool
Return True if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
In [141]: 'hello'.isupper() Out[141]: False In [142]: 'HELLO'.isupper() Out[142]: True In [143]: 'HELLO '.isupper() Out[143]: True In [144]: 'HELLO CMZ'.isupper() Out[144]: True
和islower 相反
15. join 用于将序列中的元素以指定的字符连接生成一个新的字符串
join(...)
S.join(iterable) -> string
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
In [150]: name ='hello' In [151]: '-'.join(name) Out[151]: 'h-e-l-l-o'
16. ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。
ljust(...)
S.ljust(width[, fillchar]) -> string
Return S left-justified in a string of length width. Padding is
done using the specified fill character (default is a space).
In [166]: name='caimengzhi' In [167]: name.ljust(20,'-') Out[167]: 'caimengzhi----------'
16. rjust和ljust相反
In [169]: name Out[169]: 'caimengzhi' In [170]: name.rjust(20,'-') Out[170]: '----------caimengzhi'
17. lower 方法转换字符串中所有大写字符为小写。
In [173]: 'CAIMENGZHI'.lower() Out[173]: 'caimengzhi'
18. upper和lower 相反
In [174]: name Out[174]: 'caimengzhi' In [175]: name.upper() Out[175]: 'CAIMENGZHI' In [176]: name Out[176]: 'caimengzhi'
但是都是不改变原值
19. strip() 用于移除字符串头尾指定的字符(默认为空格)。
lstrip() 去掉左侧空格
rstrip()去掉右侧空格
In [182]: ' caimengzhi '.lstrip() #去掉左侧空格 Out[182]: 'caimengzhi ' In [183]: ' caimengzhi '.rstrip() #去掉右侧空格 Out[183]: ' caimengzhi' In [184]: ' caimengzhi '.strip() # 去掉两头空格 Out[184]: 'caimengzhi'
20.partition用来根据指定的分隔符将字符串进行分割。
如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。
返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串
rpartition(...)
S.rpartition(sep) -> (head, sep, tail)
Search for the separator sep in S, starting at the end of S, and return
the part before it, the separator itself, and the part after it. If the
separator is not found, return two empty strings and S.
In [190]: str = "http://www.taobao.cc/" In [191]: str.rpartition('://') Out[191]: ('http', '://', 'www.taobao.cc/')
21. replace 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
replace(...)
S.replace(old, new[, count]) -> string
Return a copy of string S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
In [195]: str = "this is string example! this is really string"; In [196]: str.replace("is", "was") Out[196]: 'thwas was string example! thwas was really string' In [197]: str.replace("is", "was",2) # 替换两个 Out[197]: 'thwas was string example! this is really string'
22. split 通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串
split(...)
S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed
from the result.
语法
split()方法语法:
str.split(str="", num=string.count(str)).
参数
- str -- 分隔符,默认为所有的空字符,包括空格、换行( )、制表符( )等。
- num -- 分割次数。
返回值
返回分割后的字符串列表。
In [207]: 'line1 line2 lin3'.split() Out[207]: ['line1', 'line2', 'lin3']
利用re模块分割含有多种分割符的字符串:
In [212]: import re In [213]: a='My name, is; caimengzhi*is a boy' In [214]: x= re.split(',|; |*| ',a) In [215]: x Out[215]: ['My name', ' is', 'caimengzhi', 'is', '', 'a boy']
23. splitlines
描述
Python splitlines() 按照行(' ', ' ', ')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
语法
splitlines()方法语法:
str.splitlines([keepends])
参数
- keepends -- 在输出结果里是否去掉换行符(' ', ' ', '),默认为 False,不包含换行符,如果为 True,则保留换行符。
返回值
返回一个包含各行作为元素的列表。
In [217]: str1 = 'ab c de fg kl ' In [218]: print str1.splitlines(); ['ab c', '', 'de fg', 'kl']