Python不支持单字符类型,单字符也是作为一个字符串使用
s="hello world! abc"
s1="hello world!\n abc"
s2=r"hello world!\n abc"
访问子字符串,可以用方括号来截取字符串
print s[0]
print s[1:4]
print s[0:-1]
print s[2:]
h
ell
hello world! ab
llo world! abc
字符串运算符
print "h" in s
print "h" not in s
True
False
字符串前缀“r”不识别转义
print s1
print s2
hello world!
abc
hello world!\n abc
字符串大小写转换
print s.upper()
print s.lower()
print s.capitalize()
print s.title()
HELLO WORLD! ABC
hello world! abc
Hello world! abc
Hello World! Abc
字符串搜索 find rfind count __contains__
指定起始位置搜索:find('t',start)
指定起始及结束位置搜索:find('t',start,end)
从右边开始查找:rfind('t')
搜索到多少个指定字符串:count('t')
print s.find("abc")
print s.find("abcd")
print s.find("abc",0,5)
print s.rfind("l")
print s.count("l")
print s.__contains__("abc")
13
-1
-1
9
3
True
字符串替换
print s.replace("abc", "xyz")
print s.replace("abc", "xyz")
hello world! xyz
hexyzxyzo world! abc
字符串分割
print s.split(" ")
['hello', 'world!', 'abc']