Python筆記 字串操作

2021-10-16 09:08:31 字數 1980 閱讀 3118

字串相關操作

a =

'test 123 dfg test'

## 方法1

len(

[i for i in a.split(

' ')

if i == test]

)## 方法2

len(a.split(

'test'))

-1

import re 

str=

'''/begin measurement

100link

display

symbol

/end measurement'''

regex = r'/begin measurement([\s\s]*)/end measurement'

matches = re.findall(regex,

str)

for match in matches:

print

(match)

import re 

str=

'test:100 end'

regex = r'test:([\s\s]*)/end'

matches = re.findall(regex,

str)

test = matches[0]

.strip(

)

s =

' 123abcd456 '

# 刪除兩邊的空格

print

(s.strip())

# 刪除右邊空格

print

(s.rstrip())

# 刪除左邊空格

print

(s.lstrip())

# 刪除兩邊的數字

print

(s.strip(

' ')

.strip(

'123456'))

# 刪除兩邊的引號

s ="'123abcd456'"

print

(s.strip(

"'")

)

分割並去除空格

string =

" hello , world !"

string =

[x.strip(

)for x in string.split(

',')

]

string =

"dst='192.168.0.1',src='192.168.1.2'"

fields =

dict

((field.split(

'=')

for field in string.split(

',')))

fields =

dict((

(lambda a:

(a[0

].strip(

"'")

,a[1

].strip(

"'")))

(field.split(

'=')

)for field in string.split(

',')

))

>>

> fields

s =

'11233aabcdd41556'

# 刪除某個特定字元

print

(ss.replace(

'1','')

)# 同時刪除不同字元

import re

print

(re.sub(

'[1a]',''

, s)

)

--the end--

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