一、字符串方法
1.增(拼接)
2.删
Str = "hello world"
A=Str.replace("l",'pp',-1)
print(A)
*replace会产生一个新值,第一个参数是旧值,第二个参数是新值,第三个参数控制修改的次数,不添加则默认全部替换,负数则全部删除Str = "hello world"
A=Str.strip("hello")
print(A)
*删除指定的字符串,并返回一个新值
3.改
Str = " HEl lo world"
A=Str.upper()==>所有均大写,返回一个新值
A=Str.lower()==>所有均小写,返回一个新值
A=Str.split(" ")==>以什么来分割字符串,这里是以空格分割
A=Str.center(20,"0")==>设置文本长度20,并居中,不够的长度以0补齐,第二个参数必须表示成字符串
4.查
Str = "HEl lo world"
A=Str.find("El")==>返回该字符串是从哪一个位置起始的索引值,此处返回1,未找到返回-1,这是和index不同的地方
A=Str.index("HEl",4)==>从第四个位置查找该字符串,默认从头查找,未找到报错
二、字符串拼接
1.基础方法和运算
**字符串的index是查找该位置是什么字符串;列表元祖的index是查找该元素在什么位置
2.字符串格式化
3.%拼接
Str = 2.334
print("%d"%Str)==>2A = "hello"
B = "world"
print("%s %s"%(A,B))
使用%拼接和第二点格式化一样的使用方法
4.format拼接
*1.
A = "{} {}".format("hello", "world")==>"hello world"
*2.
A = "{1} {0}".format("hello", "world")==>"world hello"
*3.
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
==>网站名:菜鸟教程, 地址 www.runoob.com
*4.通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
==>网站名:菜鸟教程, 地址 www.runoob.com
*5.通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))
==>网站名:菜鸟教程, 地址 www.runoob.com
*6.数字格式化
print("{:.2f}".format(3.1415926))==>小数点后保留两位,3.14
print("{:+/-.3f}".format(3.1415926))==>带符号保留小数点后三位,+3.142,-3.142
print("{:t>9f}".format(3.1415926))==>字母t补零 (右对齐,宽度不够填充左边, 宽度为9),t3.141593
print("{:t<9f}".format(3.1415926))==>字母t补零 (左对齐,宽度不够填充右边, 宽度为9),3.141593t
print("{:^10d}".format(25))==>25,居中对齐
print("{:.2%}".format(0.25))==>百分比格式,25.00%
print("{a:x<10}".format(a=12))==>12xxxxxxxx,长度为10,数值是a,并左对齐x填充
5.join拼接
A="AA".join(["h",'s'])
print(A)==>以AA将字符串拼接起来, hAAs
三、Python内建函数
Python字符串方法官网:http://www.runoob.com/python/python-strings.html
网友评论