python字串處理

2021-10-05 01:13:48 字數 2931 閱讀 4974

問題:

過濾使用者輸入中前後多餘的空白字元

『 ++++abc123— 『

過濾某windows下編輯文字中的』\r』:

『hello world \r\n』

去掉文字中unicode組合字元,音調

「zhào qián sūn lǐ zhōu wú zhèng wáng」

如何解決以上問題?

去掉兩端字串: strip(), rstrip(),lstrip()

#!/usr/bin/python3

s =' -----abc123++++ '

# 刪除兩邊空字元

print

(s.strip())

# 刪除左邊空字元

print

(s.rstrip())

# 刪除右邊空字元

print

(s.lstrip())

# 刪除兩邊 - + 和空字元

print

(s.strip(

).strip(

'-+'))

print

("北門吹雪:"

)

#!/usr/bin/python3

s = 』 -----abc123++++ 』

print(s.strip())

print(s.rstrip())

print(s.lstrip())

print(s.strip().strip(』-+』))

print(「北門吹雪:」)

刪除單個固定位置字元: 切片 + 拼接

#!/usr/bin/python3

s ='abc:123'

# 字串拼接方式去除冒號

new_s = s[:3

]+ s[4:

]print

(new_s)

#!/usr/bin/python3

s = 『abc:123』

new_s = s[:3] + s[4:]

print(new_s)

刪除任意位置字元同時刪除多種不同字元:replace(), re.sub()

#!/usr/bin/python3

# 去除字串中相同的字元

s ='\tabc\t123\tisk'

print

(s.replace(

'\t',''

))print

("北門吹雪: "

)import re

# 去除\r\n\t字元

s ='\r\nabc\t123\nxyz'

print

(re.sub(

'[\r\n\t]',''

, s)

)

#!/usr/bin/python3

s = 『\tabc\t123\tisk』

print(s.replace(』\t』, 『』))

print(「北門吹雪: 」)

import re

s = 『\r\nabc\t123\nxyz』

print(re.sub(』[\r\n\t]』, 『』, s))

同時刪除多種不同字元:translate() py3中為str.maketrans()做對映

#!/usr/bin/python3

s ='abc123xyz'

# a _> x, b_> y, c_> z,字元對映加密

print

(str

.maketrans(

'abcxyz'

,'xyzabc'))

# translate把其轉換成字串

print

(s.translate(

str.maketrans(

'abcxyz'

,'xyzabc'))

)

#!/usr/bin/python3

s = 『abc123xyz』

print(str.maketrans(『abcxyz』, 『xyzabc』))

print(s.translate(str.maketrans(『abcxyz』, 『xyzabc』)))

去掉unicode字元中音調

#!/usr/bin/python3

import sys

import unicodedata

s ="zhào qián sūn lǐ zhōu wú zhèng wáng"

remap =

# 去除\t, \f, \r

a = s.translate(remap)

'''  通過使用dict.fromkeys() 方法構造乙個字典,每個unicode 和音符作為鍵,對於的值全部為none

然後使用unicodedata.normalize() 將原始輸入標準化為分解形式字元

sys.maxunicode : 給出最大unicode**點的值的整數,即1114111(十六進製制的0x10ffff)。

unicodedata.combining:將分配給字元chr的規範組合類作為整數返回。 如果未定義組合類,則返回0。

'''cmb_chrs =

dict

.fromkeys(c for c in

range

(sys.maxunicode)

if unicodedata.combining(

chr(c)))

#此部分建議拆分開來理解

b = unicodedata.normalize(

'nfd'

, a)

'''   呼叫translate 函式刪除所有重音符

'''print

(b.translate(cmb_chrs)

)

Python 字串處理

python endswith 方法用於判斷字串是否以指定字尾結尾,如果以指定字尾結尾返回 true 否則返回 false 可選引數 start 與 end 為檢索字串的開始與結束位置。語法 endswith 方法語法 str.endswith suffix start end 引數 返回值 如果字...

Python字串處理

去空格及特殊符號 s.strip lstrip rstrip 複製字串 strcpy sstr1,sstr2 sstr1 strcpy sstr2 sstr1 sstr1 strcpy2 print sstr2連線字串 strcat sstr1,sstr2 sstr1 strcat sstr1 ss...

Python字串處理

python字串處理 part i 常見處理函式 string.find sub,start 0,end len string 檢測sub是否包含在string中,如果是返回 第乙個sub 開始的索引值,否則返回 1.string.index sub,start 0,end len string 跟...