1.常见的字符串方法:
-
isalpha():检验字符串是否全是字母,返回布尔:
isalpha(...)
S.isalpha() -> boolReturn True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.
>>> "Python".isalpha()
True
>>> "123Python".isalpha()
False
- split()方法:以指定的分隔符分割字符串,返回列表
>>> string="I like Python"
>>> string.split(" ")
['I', 'like', 'Python']
>>> string2="www.sina.com"
>>> string2.split('.')
['www', 'sina', 'com']
若指定的分隔符不存在,则返回整个列表字符串(可以利用此方法,将字符串转换成列表):
>>> string.split('.')
['I like Python']
注意,与list函数是有区别的,比如:
>>> list(string)
['I', ' ', 'l', 'i', 'k', 'e', ' ', 'P', 'y', 't', 'h', 'o', 'n']
还可以指定分割的次数:
>>> string3="www..sina..com"
>>> string3.split('.',2)
['www', '', 'sina..com']
- strip():去掉字符串两端的空格
lstrip():去掉左端空格
rstrip():去掉右端空格
>>> string=" Hello "
>>> string.strip()
'Hello'
>>> string #string本身的值并没有发生改变
' Hello '
>>> string.lstrip()
'Hello '
>>> string.rstrip()
' Hello'
- 字母的大小写判断:
>>> string1="King"
>>> string1.upper() #全部转换为大写
'KING'
>>> string1.lower() #全部转换为小写
'king'
>>>
>>> string2='this is an example'
>>> string2.capitalize() #首字母大写
'This is an example'
>>> string1.isupper() #是否全部大写
False
>>> string2.islower() #是否全部小写
True
>>> string3="Jim Green"
>>> string3.iscapitalize() #不存在的函数
Traceback (most recent call last):
File "", line 1, in
string3.iscapitalize()
AttributeError: 'str' object has no attribute 'iscapitalize'
>>> string3.istitle() #判断各个单词首字母是否大写.
True
>>> string4.title() #各个单词首字母变大写.
'This Is A Book.'
- 拼接函数---join(),注意原来是使用"+"号进行拼接的:
Help on method_descriptor:
join(...)
S.join(iterable) -> str
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
>>> string="www.sina.com"
>>> text1=string.split('.')
>>> text1
['www', 'sina', 'com']
#join()传入的是一个可迭代对象,传入字符串也是OK的...
>>> text2=".".join(text1)
>>> text2 #join()不仅拼接了字符串,而且还转换成了文本格式,不再是列表,刚好与split()相反.
'www.sina.com'
小补:
string转换成list,最直接的方法是str.split()
而不是list(string)