目录
1.字符串
普通字符串
'hello world'
"hello world"
'hello "world'
"hello 'world"
"hello \"world"
原始字符串
r'hello \n world'
长字符串
s="""
《早发白帝城》
朝辞白帝彩云间,千里江陵一日还。
两岸猿声啼不住,轻舟已过万重山。
"""
print(r)
2.字符串与数字转换
int("80")
float('80.0')
int('AB',16)
3.数字转换为字符串
主要利用 str() 函数
str(80)
str(True)
4.格式化字符串
i = 32
str_sample = "i * i = {}".format(i * i)
print(str_sample)
str_sample = "i * i = {}".format(i * i)
print(str_sample)
str_sample = "{0} * {0} = {1}".format(i, i * i)
print(str_sample)
str_sample = "{p1} * {p1} = {p2}".format(p1 = i,p2 = i * i)
print(str_sample)
5.格式化控制符
salary = 5834.5678
name = "Tony"
s="{0:s}年龄{1:d},工资是{2:f}元。".format(name,20,salary)
print(s)
salary = 5834.5678
name = "Tony"
s="{0}年龄{1},工资是{2:0.2f}元。".format(name,20,salary)
print(s)
salary = 5834.5678
name = "Tony"
s="{0}年龄{1},工资是{2:G}元。".format(name,20,salary)
print(s)
salary = 5834.5678
name = "Tony"
s="{0}年龄{1},工资是{2:g}元。".format(name,20,salary)
print(s)
salary = 5834.5678
name = "Tony"
s="{0}年龄{1},工资是{2:e}元。".format(name,20,salary)
print(s)
salary = 5834.5678
name = "Tony"
s="{0}年龄{1},工资是{2:E}元。".format(name,20,salary)
print(s)
s="十进制数{0:d}的八进制表示为{0:o}。".format(18)
print(s)
s="十进制数{0:d}的十六进制表示为{0:X}。".format(18)
print(s)
"十进制数{0:d}的十六进制表示为{0:x}。".format(18)
print(s)
6.字符串查找
s = "Hello World"
print(s.find('e'))
print(s.find('l'))
print(s.find('l',4))
print(s.find('l',4,6))
7.字符串替换
s= "AB CD EF GH IJ"
print(s.replace(' ','|',2)) # replace(old, new[,count])
print(s.replace(' ','|'))
print(s.replace(' ','|',1))
8.字符串分割
s= "AB CD EF GH IJ"
print(s.split(' '))
print(s.split(' ',maxsplit = 0))
print(s.split(' ',maxsplit = 1))
print(s.split(' ',maxsplit = 2))