本文共 2188 字,大约阅读时间需要 7 分钟。
a = 'lao'b = 'wang'd = a + be = "===%s===" % (a+b) #a与b必须都是字符串print(d)print(e)
name = 'abcdef'print(name[0])print(name[5])print(name[len(name)-1])print(name[-1])
name = 'abcdefABCDEF'#切片语法:string[起始位置:终止位置:步长]print(name[2:5]) #cdeprint(name[2:]) #cdefABCDEFprint(name[2:-2]) #cdefABCDprint(name[2:-1:2]) #ceACEprint(name[0:])#以下写法将字符串逆序print(name[-1::-1]) #FEDCBAfedcbaprint(name[::-1]) #前面两个都省略,关键看后面的步长
#coding=utf-8myStr = "hello world and we are the world"print(myStr.count("world")) #2#统计字符串出现的次数,如果没有则返回0print(myStr.replace("world","WORLD")) #hello WORLD and we are the WORLD#注意:replace不会对原字符串产生任何影响print(myStr.replace("world","xxxxx",1)) #hello xxxxx and we are the world#replace第一个参数为:要替换的字符串,第二个参数为:替换成什么字符串,第三个参数为:如果要替换的字符串出现多次那么要替换的个数print(myStr.split(" ")) #['hello', 'world', 'and', 'we', 'are', 'the', 'world']print(myStr.capitalize()) #Hello world and we are the worldfile_name = "xxxxx.txt"print(file_name.endswith(".txt")) #True#ljust , rjust , centerlyric = "Tonight , I feel close to you"print(lyric.center(50)) # Tonight , I feel close to you print(lyric.ljust(50))print(lyric.rjust(50))#lstrip , rstrip , stripname = " who are you "print(name.lstrip())print(name.rstrip())print(name.strip())#partition , rpatitionprint(myStr.partition("world")) #('hello ', 'world', ' and we are the world')print(myStr.rpartition("world")) #('hello world and we are the ', 'world', '')#spliteline 按照换行符进行分隔content = "hello\nworld\nxxx\nyyy"print(content.splitlines()) #['hello', 'world', 'xxx', 'yyy']#isalpha 判断是否是纯字母#isdigit 判断是否是纯数字#isalnum 判断是否是字母与数字#joina = ['aaa','bbb','ccc']b = '='print(b.join(a)) #aaa=bbb=cccb = ' 'print(b.join(a)) #aaa bbb ccc
面试题:给定一个字符串str,返回使用空格或者'\t'分割后的倒数第二个子串
str = "haha nihao a \t heihei \t woshi nide \t hao \npenyou"print(str)sstr = str.split()print(sstr) #['haha', 'nihao', 'a', 'heihei', 'woshi', 'nide', 'hao', 'penyou']print(' '.join(sstr))
转载于:https://blog.51cto.com/12332406/2047832