string比较连接
>>> s1="python string" >>> len(s) 13 >>> s2=" python string2 " >>> s=s1+s2 >>> s ‘python string python string2 ‘ >>> >>> cmp(s1,s2) 1
string 截取
>>> s1[0] ‘p‘ >>> s1[-1] ‘g‘ >>> s1[0:5] ‘pytho‘ >>> s1[1:] ‘ython string‘ >>> s1[::-1] ‘gnirts nohtyp‘ >>> s1 ‘python string‘ >>> s1[2:-1] ‘thon strin‘ >>> s1[:8:-1] ‘gnir‘ >>> s1[::2] ‘pto tig‘ >>> s1[::-2] ‘git otp‘ >>> s1[5::-2] ‘nhy‘ >>> s1[:5:-2] ‘git ‘
string搜索和替换
>>> s3="onnoonssss" >>> s3.count("s") 4 >>> s3.count("ss") 2 >>> s3.count("on") 2 >>> s3.count("no") 1 >>> s4="sssnnnsss" >>> s4.index("s") 0 #rindex 从右边算起的第一次出现的也就是index的逆序 >>> s4.rindex("s") 8 >>> s4.index("s",4) 6 >>> s4.index("n") 3 >>> s4.index("n",4) 4 #如果搜索的字符没有,则报错 >>> s4.index("g") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found >>> s4.find("s") 0 >>> s4.find("s",5) 6 #如果搜索的字符没有则-1 >>> s4.find("g",5) -1 >>> s4.replace("s","g") ‘gggnnnggg‘ >>> s4.replace("ss","g") ‘gsnnngs‘ #S.replace(oldstr, newstr, [count]) 把S中的oldstr替换为newstr,count为替换次数 >>> s4.replace("s","g",1) ‘gssnnnsss‘ >>> s4.replace("s","g",2) ‘ggsnnnsss‘ >>> s2 ‘ python string2 ‘ >>> s2.strip() ‘python string2‘ >>> s2.lstrip() ‘python string2 ‘ >>> s2.rstrip() ‘ python string2‘ >>> s="* python * * string *" >>> s.strip("*") ‘ python * * string ‘ >>> s.lstrip("*") ‘ python * * string *‘
string分割组合
#S.split([sep, [maxsplit]]) #以sep为分隔符,把S分成一个list。maxsplit表#示分割的次数。默认的分割符为空白字符 >>> s2 ‘ python string2 ‘ >>> s2.split(" ") [‘‘, ‘‘, ‘python‘, ‘string2‘, ‘‘] >>> s2.split(" ",1) [‘‘, ‘ python string2 ‘] >>> s2.rsplit(" ",1) [‘ python string2‘, ‘‘] #S.splitlines([keepends]) #把S按照行分割符分为一个list,keepends是#一个bool值,如果为真每行后而会保留行分割符。 >>> s5=""" ... first line ... second line ... """ >>> s5.splitlines() [‘‘, ‘first line‘, ‘second line‘] #str.join(sequence) sequence -- 要连接的元素序列 返回通过指定字符 #连接序列中元素后生成的新字符串。 >>> "-".join(s1) ‘p-y-t-h-o-n- -s-t-r-i-n-g‘
string测试
>>> s ‘python string python string2 ‘ >>> s1.isupper() False >>> s1.islower() True #是否全是空白字符,并至少有一个字符 >>> s1.isspace() False #是否全是数字,并至少有一个字符 >>> s.isdigit() False #是否全是字母,并至少有一个字符 >>> s.isalpha() False #是否全是字母和数字,并至少有一个字符 >>> s.isalnum() False #是否是首字母大写的 >>> s.istitle() False #str.startswith(str, beg=0,end=len(string)); >>> s ‘ Python string !! ‘ >>> s.startswith(" P") True >>> s.endswith(" ") True >>> s.startswith("P",2) True >>> s.startswith("P",3) False >>>
string输出对齐
#输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格 >>> s.ljust(50,"s") ‘ Python string !! sssssssssssssssssssssssssssss‘ #右对齐 >>> s.rjust(50,"s") ‘sssssssssssssssssssssssssssss Python string !! ‘ #中间对齐 >>> s.center(50,"c") ‘cccccccccccccc Python string !! ccccccccccccccc‘ #把S变成width长,并在右对齐,不足部分用0补足 >>> s.zfill(50) ‘00000000000000000000000000000 Python string !! ‘
string大小写
>>> s1.lower() ‘python string‘ >>> s1.upper() ‘PYTHON STRING‘ #大小写互换 >>> s1.swapcase() ‘PYTHON STRING‘ >>> s1.capitalize() ‘Python string‘ >>> s1.title() ‘Python String‘
时间: 2024-10-19 04:00:20