🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[toc] ## **字符串基础知识** 在Python中,加了引号的字符都被认为是字符串,字符串也可以像list列表一样通过下标引用 ```python >>> name = "Alex Li" #双引号 >>> age = "22" #只要加引号就是字符串 >>> age2 = 22 #int >>> msg = '''My name is Alex, I am 22 years old!''' #3个引号也可以 >>> hometown = 'ShanDong' #单引号也可以 ``` ### 单双多引号的区别 * 单双引号的区别 木有任何区别,只有下面这种情况,需要考虑单双的配合 `msg = "My name is Alex , I'm 22 years old!" ` * 多引号的作用呢 作用就是多行字符串必须用多引号 ``` msg = ''' 今天我想写首小诗, 歌颂我的同桌. ''' print(msg) ``` ### 字符串拼接 字符串呢只能进行"相加"和"相乘"运算。 ```python >>> name 'Alex Li' >>> age '22' >>> >>> name + age #相加其实就是简单拼接 'Alex Li22' >>> >>> name * 10 #相乘其实就是复制自己多少次,再拼接在一起 'Alex LiAlex LiAlex LiAlex LiAlex LiAlex LiAlex LiAlex LiAlex LiAlex Li' ``` > 注意: > 字符串的拼接只能是双方都是字符串,不能跟数字或其它类型拼接 > 字符串的单引号和双引号都无法取消特殊字符的含义,如果想让引号内所有字符均取消特殊意义,在引号前面加r,如`name=r'l\thf'` ## **字符串常用方法** ### 字符串索引 ``` >>> name='hello word' >>> name[2] 'l' >>> name[1] 'e' >>> name.index('o') 4 ``` ### 字符串切片 ``` >>> name='hello word' >>> name[1:4] 'ell' >>> name[:4] 'hell' ``` ### 判断是否纯数字`isdigit` ```python >>> name1='222';name2='aaa';name3='22aa' >>> name1.isdigit(),name2.isdigit(),name3.isdigit() (True, False, False) ``` ### 字符串替换`replace` ``` >>> name='hello word omg' >>> name.replace('o','X') 'hellX wXrd Xmg' >>> name.replace('o','X',1) #只替换一个 'hellX word omg' ``` ### 字符串查找`find` ``` >>> name='hello word omg' >>> name.find('o') 4 >>> name.find('o',5) #从第5个开始查找 7 >>> name.rfind('o') #从右边开始查找 11 ``` ### 字符串统计`count` ``` >>> name='hello word omg' >>> name.count('o') 3 >>> name.count('l') 2 ``` ### 取消前后空格`strip` ``` >>> name=' hello word omg ' >>> name.strip() 'hello word omg' ``` ### 字符串居中填补`center` ``` >>> name='hello word omg' >>> name.center(30,'-') #30个字符长度,不够就用指定字符代替(默认空格) '--------hello word omg--------' >>> name.center(30) ' hello word omg ' ``` ### 字符串**格式化**`format` * 用`%s`格式化 ``` >>> print('my %s is %s'%('name','noah')) my name is noah >>> name='my %s is %s'%('name','noah') >>> name 'my name is noah' ``` * 用`format`格式化 ``` #1.不指定序号 >>> name="my name is {},my age is {}" >>> name.format('noah',22) 'my name is noah,my age is 22' #2.指定序号 >>> name="my name is {0},my age is {1},this is {1}" >>> name.format('noah',22,'haha') 'my name is noah,my age is 22,this is 22' #3.用变量名代替序号 >>> name="my name is {name},my age is {age}" >>> name.format(name='noah',age=22) 'my name is noah,my age is 22' ``` ### 字符串连接`join` ``` >>> name=['hello','word','ok'] >>> '+'.join(name) 'hello+word+ok' >>> '-'.join(name) 'hello-word-ok' ``` ### 字符串切割`split` ``` >>> name='hello word omg' >>> name.split() #默认用空格进行切割 ['hello', 'word', 'omg'] >>> name.split('o') #指定过切割字符 ['hell', ' w', 'rd ', 'mg'] >>> name.split('o',1) #指定切割个数 ['hell', ' word omg'] ```