Python 字串操作

2021-07-11 10:47:05 字數 2943 閱讀 3199

去空格及特殊符號

s.strip().lstrip().rstrip(',')

複製字串

#strcpy(sstr1,sstr2)

sstr1 = 'strcpy'

sstr2 = sstr1

sstr1 =

'strcpy2'

print sstr2

連線字串

#strcat(sstr1,sstr2)

sstr1 = 'strcat'

sstr2 =

sstr1 += sstr2

print sstr1

查詢字元

#strchr(sstr1,sstr2)

# < 0

為未找到

sstr1 = 'strchr'

sstr2 =

's'npos = sstr1.index(sstr2)

print npos

比較字串

#strcmp(sstr1,sstr2)

sstr1 = 'strchr'

sstr2 =

'strch'

print cmp(sstr1,sstr2)

掃瞄字串是否包含指定的字元

#strspn(sstr1,sstr2)

sstr1 = '12345678'

sstr2 =

'456'

#sstr1 and chars both in sstr1 and sstr2

print len(sstr1 andsstr2)

字串長度

#strlen(sstr1)

sstr1 = 'strlen'

print len(sstr1)

將字串中的大小寫轉換

#strlwr(sstr1)

sstr1 = 'jcstrlwr'

sstr1 = sstr1.upper()

#sstr1 = sstr1.lower()

print sstr1

追加指定長度的字串

#strncat(sstr1,sstr2,n)

sstr1 = '12345'

sstr2 =

'abcdef'

n = 3

sstr1 += sstr2[0:n]

print sstr1

字串指定長度比較

#strncmp(sstr1,sstr2,n)

sstr1 = '12345'

sstr2 =

'123bc'

n = 3

print cmp(sstr1[0:n],sstr2[0:n])

複製指定長度的字元

#strncpy(sstr1,sstr2,n)

sstr1 = ''

sstr2 =

'12345'

n = 3

sstr1 = sstr2[0:n]

print sstr1

將字串前n個字元替換為指定的字元

#strnset(sstr1,ch,n)

sstr1 = '12345'

ch =

'r'n = 3

sstr1 = n * ch + sstr1[3:]

print sstr1

掃瞄字串

#strpbrk(sstr1,sstr2)

sstr1 = 'cekjgdklab'

sstr2 =

'gka'

npos = -1

for c in

sstr1:

ifc in

sstr2:

npos = sstr1.index(c)

break

print npos

翻轉字串

#strrev(sstr1)

sstr1 = 'abcdefg'

sstr1 = sstr1[::-1]

print sstr1

查詢字串

#strstr(sstr1,sstr2)

sstr1 = 'abcdefg'

sstr2 =

'cde'

print sstr1.find(sstr2)

分割字串

#strtok(sstr1,sstr2)

sstr1 = 'ab,cde,fgh,ijk'

sstr2 =

','sstr1 = sstr1[sstr1.find(sstr2) + 1:]

print

sstr1#或者

s = 'ab,cde,fgh,ijk'

print(s.split(','))

連線字串

delimiter = ','

mylist = [

'brazil', 'russia', 'india','china'

]print delimiter.join(mylist)

php 中 addslashes 的實現

defaddslashes(s):

d =

return

''.join(d.get(c, c) forc in

s)s = "john 'johny' doe (a.k.a.\"super joe\")\\\0"

print

sprint addslashes(s)

只顯示字母與數字

def onlycharnum(s,oth=''

):s2 = s.lower();

fomart = 'abcdefghijklmnopqrstuvwxyz0123456789'

for cin

s2:if

not c in

fomart:

s = s.replace(c,''

);return

s;print(onlystr("a000aa-b"))

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開...