字符串,内置类型,一般放在单引号、双引号、三引号中。
提取字符串中的一个字符——索引运算
例如:a = "Hello"
则a[4]返回'o'
提取一个子字符串——切片运算符
例如:
>>> s = 'Hello World'
>>> a[:5]
Traceback (most recent call last):
File "", line 1, in
NameError: name 'a' is not defined
>>> s = 'Hello World'
>>> s[:5]
'Hello'
>>> s[-1:5]
''
>>> s[0:5]
'Hello'
>>> s[6:5]
''
>>> s[6:]
'World'
>>> s[6:9]
'Wor'
>>> s[6:-1]
'Worl'
>>> s[6:0]
''
>>>
连接多个字符串——使用加(+)运算符
例如:
>>> s = 'Hello World'
>>> s = s + '!nihao'
>>> s
'Hello World!nihao'
>>> s = '1'+'2'+'3' #python绝对不会将字符串的值解释为数值数据(Perl、php会出现此问题)
>>> s
'123'
>>> 'aa'+4 #不同类型相加会报错
Traceback (most recent call last):
File "", line 1, in
TypeError: cannot concatenate 'str' and 'int' objects
将字符串转换为数值数据:
使用int()、float()
例如:
>>> x = 23
>>> y = 32
>>> x = "23"
>>> y = "32"
>>> z = x+y
>>> z
'2332'
>>> z = int(x) + int(y)
>>> z
55
>>> z = float(x) + float(y)
>>> z
55.0
>>> x = "as12"
>>> int(x) #引发ValueError异常
Traceback (most recent call last):
File "", line 1, in
ValueError: invalid literal for int() with base 10: 'as12'
>>>
将非字符串值转化为字符串:
使用str()、repr()、format()
例如:
>>> x = 23
>>> str(x)
'23'
>>> str(23)
'23'
>>> repr(x)
'23'
>>> str(2.3)
'2.3'
>>> repr(2.3)
'2.3'
>>> format(x,'0.5f')
'23.00000'
>>> format(2.3,'0.5f')
'2.30000'
获取字符串长度
len(string)
在字符串中使用占位符
>>> a = "hello {0},{1}"
>>> a
'hello {0},{1}'
>>> a.format("Bob")
Traceback (most recent call last):
File "", line 1, in
IndexError: tuple index out of range
>>> a.format("Bob","Alice")
'hello Bob,Alice'
>>> b = "hello,{0},{num}"
>>> b.format("Bob",num=20)
'hello,Bob,20'
>>>
转义字符转义字符描述
\(在行尾时)
续行符
\\
反斜杠符号
\'
单引号
\"
双引号
\a
响铃
\b
退格(Backspace)
\e
转义
\000
空
\n
换行
\v
纵向制表符
\t
横向制表符
\r
回车
\f
换页
\oyy
八进制数yy代表的字符,例如:\o12代表换行
\xyy
十进制数yy代表的字符,例如:\x0a代表换行
\other
其它的字符以普通格式输出
原始字符串(RAW STRING)
原始字符串以R或者r开头,在原始字符串中\不再有转义字符的含义,原始字符串不能以单个\结尾。
在正则表达式中使用比较方便。
>>> s = r'as\\'
>>> s
'as\\\\'
>>> print s
as\\
>>> s = R'as\'
File "", line 1
s = R'as\'
^
SyntaxError: EOL while scanning string literal
>>> s = R'as\asd'
>>> s
'as\\asd'
>>> print s
as\asd
字符串方法
字符串方法,中括号表示可选参数
方法
描述
s.captitalize()
首字符大写
s.center(width[ , pad])
在长度为width的字段中将字串s居中。pad是填充字符。
s.count(sub[ ,start [,end]])
计算指定子字符串sub的出现次数
s.decode([encoding [,errors]])
解码一个字符串并返回一个Unicode字符串(只能用
于字节字符串)
s.encode([encoding [,errors]])
返回字符串的编码版本(只能用于Unicode字符串)
s.endswith(suffix [,start [,end]])
检查字符串是否以suffix结尾
s.expandtabs([tabsize])
使用空格代替制表符
s.find(sub [,start [,end]])
返回子字符串sub首次出现的位置,若无,返回-1
s.format(*args,*kwargs)
格式化s
s.index(sub [,start [,end]])
返回子字符串sub首次出现的位置,若无,报错ValueError
s.isalnum()
检查所有字符是否都为字母或都为数字,返回Ture或False
s.isalpha()
检查所有字符是否都为字母
s.isdigit()
检查所有字符是否都为数字
s.islower()
检查所有字符是否都为小写
s.isspace()
检查所有字符是否都为空白
s.istitle()
检查字符串是否为标题字符串(每个单词首字母大写)
s.isupper()
检查所有字符是否都为大写
s.joit(t)
使用s作为分割符连接序列t中的字符串,返回字符串
s.ljust(width [,fill])
在长度为width的字符串内左对齐s
s.lower()
将s中的大写字母转换为小写形式,返回字符串
s.lstrip([chrs])
若有chrs参数且s头部是chrs,删除头部chrs,返回结果,
若无,返回s;若无chrs参数,删除左边空白
s.partition(sep)
使用字串sep划分字符串s。返回一个元组(head,sep,tail)。
若未找到sep,返回(s,"","")
s.replace(old,new [,maxreplace])
替换一个子字符串
s.rfind(sub [,start [,end]])
找到一个子字符串最后一次出现的位置
s.rindex(sub [,start [,end]])
找到一个子字符串最后出现的位置,否则报错
s.rjust(width [,fill])
在长度为width的字符串中右对齐s
s.rpartition(sep)
使用字串sep划分字符串s,但是从字符串的结尾处开始搜索
s.rsplit([sep [,maxsplit]])
使用sep作为分隔符对s从后向前进行划分。maxsplit是划分的
最大次数。若省略maxsplit,结果与split()方法完全相同。
s.rstrip([chrs])
类似lstrip(),不过是针对s尾部
s.split([sep [,maxsplit]])
使用sep作为分隔符对s划分,maxsplit是划分的最大次数,返回
列表
s.splitlines([keepends])
将字符串分为一个行列表,若keepends为1,则保留各行最后的换行符
s.startswith(prefix [,start [,end]])
检查一个字符串是否以prefix开头,返回True/False
s.strip([chrs])
若有chrs参数,若s头部或尾部有chrs,则删除头部和尾部的chrs,
并返回处理后的字符串;若无chrs,删除头部和尾部的空白。
s.swapcase()
将大写转换为小写,小写转换为大写。
s.title()
将字符串转化为标题格式
s.translate(table [,deletechars])
使用一个字符串转换表table转换字符串,删除deletechars中的字符
s.upper()
将s转换为大写
s.zfill(width)
在字符串的左边填充0,直到其宽度为width
代码示例:
a='hello'
printa
a="Hello"
printa
b=" World!"
c=a+b
printc
#当一行写不完时使用 \
print"Hello \
World!"
str1="Hello\
World!"
printstr1
print'''''''
Hi,
python,i like u
'''
print"""
Hi,
python,i like u,too
"""
print"\n字符串和数字的转换"
printfloat("1e-1")
printfloat("12")
printint("12")
printlong("12")
printint("11",2)#11为二进制,转换为10进制
printlong("f",16)#同上
print"Hello"+" "+"world!"
print"\n关于字母大小写"
print"hello world".capitalize()#首字母大写
print"Hello world1哈啊和".capitalize()
print" 全部变为小写"
print"HELLO WoRld哈啊和".lower()
print" 全部变为大写"
print"HELLO WoRld".upper()
print"大小写互换"
print"hello WORLD".swapcase()
print("\n")
a="hello"
printa,"的长度为",len(a)
printa[-1]
printa[0]
printa[3]
printa[-2]
printa[:]
com=raw_input('\ninput a string which have blank>>')
com=com.replace(' ','_')
printcom
print'\nhello ,mymymy'
#可以在三引号中自由的使用单引号和双引号
a='''''''
hello
how are you
'''
printa
a="""
hello
how are you
"""
printa
运行结果为:
hello
Hello
Hello World!
Hello World!
Hello World!
Hi,
python,i like u
Hi,
python,i like u,too
字符串和数字的转换
0.1
12.0
12
12
3
15
Hello world!
关于字母大小写
Hello world
Hello world1哈啊和
全部变为小写
hello world哈啊和
全部变为大写
HELLO WORLD
大小写互换
HELLO world
hello 的长度为 5
o
h
l
l
hello
input a string which have blank>>q aasfas
q_aasfas
hello ,mymymy
hello
how are you
hello
how are you