python 字符串处理

jopen 10年前
1.In and not in 

>>> string = "this is a string".split()
如果字符串包含在字符中则放回真,如果不包含在字符串中则返回假
>>> "a" in string   
True
>>> "b" in string
False
如果字符串不再另外一个字符串中,则返回真,如果在则返回假
>>> "b" not in string
True

2.find and  index

>>> string = "this is a string".split()
判断字符串在另外一个字符串中的什么位置
>>> string.split().index("this")
0
>>> string.split().index("is")
1
>>> string.split().index("a")
2
>>> string.split().index("string")
3

3. startswith() 和endswith()

>>>string = "this is a string"
>>> string.startswith("this")
True
>>> string.endswith("string")
True

4. lstrip()、retrip()和strip
可以去掉前后的空格,也可以删除前后的任何内容
lstrip() 取出删除前导空白
retrip() 删除结尾空白
strip() 删除前后空白

>>> spacious_string = "\n\t Some Non-Spacious Test\n \t\r"
>>> print spacious_string
  Some Non-Spacious Test
 
>>> spacious_string.lstrip()   
'Some Non-Spacious Test\n \t\r'
>>> spacious_string.rstrip()
'\n\t Some Non-Spacious Test'
>>> spacious_string.strip()
'Some Non-Spacious Test'

>>> xml_tag = "<some_tag>"
>>> xml_tag
'<some_tag>'
>>> xml_tag.lstrip('<')
'some_tag>'
>>> xml_tag.rstrip(">")
'<some_tag'
>>> xml_tag.strip("<>")
'some_tag'

upper() 和 lower()


lower  返回的是小写的字符串 
upper 返回的是大写的字符串
>>> mixed_case_string = "VOrpal Bunny"
>>> mixed_case_string == "vorpal bunny"
False
>>> mixed_case_string.lower() == "vorpal bunny"
True
>>> mixed_case_string == "VORPAL BUNNY"
False
>>> mixed_case_string.upper() == "VORPAL BUNNY"
True
>>> mixed_case_string.lower()
'vorpal bunny'
>>> mixed_case_string.upper()
'VORPAL BUNNY'

split()

split() 把希望作为分隔符的分隔字符串传递给它,无论是管道符还是其它的都属于字符串

1。下面是以管道符传递给split(),默认的分隔符是逗号或空格。
>>> comma_delim_string = "pos1,pos2,pos3"
>>> comma_delim_string
'pos1,pos2,pos3'
>>> pipe_delim_string = "pipepos1|pipepos2|pipepos3"
>>> comma_delim_string.split()
['pos1,pos2,pos3']
>>> pipe_delim_string.split("|")
['pipepos1', 'pipepos2', 'pipepos3']
2。以字符串字幕或数字作为分隔符,下面的例子是abc也可以是其它 
>>> a = "1abc2abc3"
>>> a.split("abc")
['1', '2', '3']
3. 根据定界符第几次出现的次数进行分割
>>> string_1 = "hello,what are you doing,thanks,i'm fine"
>>> string_1
"hello,what are you doing,thanks,i'm fine"
>>> string_1.split(',',1)
['hello', "what are you doing,thanks,i'm fine"]
>>> string_1.split(',',2)
['hello', 'what are you doing', "thanks,i'm fine"]
>>> string_1.split(',',3)
['hello', 'what are you doing', 'thanks', "i'm fine"]
4。splitlines()  对多行文本按照行的方式进行分割
>>> string_2 = """what's you name
My name is james,
and you
"""
>>> string_2
"what's you name\nMy name is james,\nand you\n"
>>> string_2.split()
["what's", 'you', 'name', 'My', 'name', 'is', 'james,', 'and', 'you']
>>> string_2.splitlines()
["what's you name", 'My name is james,', 'and you']


join()

join()函数进行字符串的合并,多个字符串合并到一起
>>> string_3 = ['a','b','c','d']
>>> string_3
['a', 'b', 'c', 'd']
>>>
>>> ','.join(string_3)
'a,b,c,d'
>>> '@'.join(string_3)
'a@b@c@d'


replace()

字符串的替换
>>> string_5 = "My name is james"
>>> string_5.replace("james","alex")
'My name is alex'