python 字串操作(string替換、刪除、擷取、複製、連線、比較、查詢、包含、大小寫轉換、分割等)
去空格及特殊符號
s.strip() .lstrip() .rstrip(',')
複製字串
#strcpy(sstr1,sstr)
sstr= 'strcpy'
sstr = sstr
sstr= 'strcpy'
print sstr
連線字串
#strcat(sstr1,sstr)
sstr= 'strcat'
sstr+= sstr
print sstr
查詢字元
#strchr(sstr1,sstr)
sstr= 'strchr'
sstr = 's'
npos = sstr1.index(sstr)
print npos
比較字串
#strcmp(sstr1,sstr)
sstr= 'strchr'
sstr = 'strch'
print cmp(sstr1,sstr)
掃瞄字串是否包含指定的字元
#strspn(sstr1,sstr)
sstr= '1345678'
sstr = '456'
#sstrand chars both in sstrand sstr
print len(sstrand sstr)
字串長度
#strlen(sstr1)
sstr= 'strlen'
print len(sstr1)
將字串中的大小寫轉換
#strlwr(sstr1)
sstr= 'jcstrlwr'
sstr= sstr1.upper()
#sstr= sstr1.lower()
print sstr
追加指定長度的字串
#strncat(sstr1,sstr,n)
sstr= '1345'
sstr = 'abcdef'
n = 3
sstr+= sstr[0:n]
print sstr
字串指定長度比較
#strncmp(sstr1,sstr,n)
sstr= '1345'
sstr = '13bc'
n = 3
print cmp(sstr1[0:n],sstr[0:n])
複製指定長度的字元
#strncpy(sstr1,sstr,n)
sstr= ''
sstr = '1345'
n = 3
sstr= sstr[0:n]
print sstr
將字串前n個字元替換為指定的字元
#strnset(sstr1,ch,n)
sstr= '1345'
ch = 'r'
n = 3
sstr= n * ch + sstr1[3:]
print sstr
掃瞄字串
#strpbrk(sstr1,sstr)
sstr= 'cekjgdklab'
sstr = 'gka'
npos = -1
for c in sstr1:
if c in sstr:
npos = sstr1.index(c)
break
print npos
翻轉字串
#strrev(sstr1)
sstr= 'abcdefg'
sstr= sstr1[::-1]
print sstr
查詢字串
#strstr(sstr1,sstr)
sstr= 'abcdefg'
sstr = 'cde'
print sstr1.find(sstr)
分割字串
#strtok(sstr1,sstr)
sstr= 'ab,cde,fgh,ijk'
sstr = ','
sstr= sstr1[sstr1.find(sstr) + 1:]
print sstr
或者
s = 'ab,cde,fgh,ijk'
print(s.split(','))
連線字串
delimiter = ','
mylist = ['brazil', 'russia', 'india', 'china']
print delimiter.join(mylist)
php 中 addslashes 的實現
def addslashes(s):
d =
return ''.join(d.get(c, c) for c in s)
s = "john 'johny' doe (a.k.a. \"super joe\")\\\0"
print s
print addslashes(s)
只顯示字母與數字
def onlycharnum(s,oth=''):
s = s.lower();
fomart = 'abcdefghijklmnopqrstuvwxyz013456789'
for c in s:
if not c in fomart:
s = s.replace(c,'');
return s;
print(onlystr("a000 aa-b"))
if else語句
if filename != "softirq_hi_rrd":
string += (filename + " varchar(30), ")
else:
string += (filename + " varchar(30) ")
Python字串操作
1 複製字串 str2 str1 2 鏈結字串 str abc 3 查詢字串 string.find sub string.index sub string.rfind sub string,rindex sub 4 字串比較 cmp str1,str2 cmp str1.upper str2.up...
Python字串操作
python如何判斷乙個字串只包含數字字元 python 字串比較 下面列出了常用的python實現的字串操作 strcpy sstr1,sstr2 sstr1 strcpy sstr2 sstr1 sstr1 strcpy2 print sstr2 strcat sstr1,sstr2 sstr1...
python字串操作
在 python 有各種各樣的string操作函式。在歷史上string類在 python 中經歷了一段輪迴的歷史。在最開始的時候,python 有乙個專門的string的module,要使用string的方法要先import,但後來由於眾多的 python 使用者的建議,從 python 2.0開...