• 招生咨詢熱線:4008-569-579 
  • 手機(jī)版
    用手機(jī)掃描二維碼直達(dá)商品手機(jī)版
招生咨詢熱線
4008-569-579
機(jī)構(gòu)主頁(yè) > 培訓(xùn)資料 > Python中的字符處理技巧你都了解嗎
機(jī)構(gòu)主頁(yè) > 培訓(xùn)資料>Python中的字符處理技巧你都了解嗎

Python中的字符處理技巧你都了解嗎

來(lái)源:廣州達(dá)內(nèi)教育        時(shí)間:2023-05-31        熱度:121℃        返回列表

Python是一門(mén)非常流行的開(kāi)發(fā)語(yǔ)言了,python現(xiàn)在會(huì)這么的收歡迎不止是因?yàn)槿斯ぶ悄艿膸?dòng),有很大的一部分是因?yàn)樗潜容^簡(jiǎn)單易學(xué)的,但是在使用python的時(shí)候有很多的字符的處理技巧你知道嗎?這些處理技巧可以讓你的工作更加的便捷。

Python中的字符處理技巧你都了解嗎

一. 空格剝離

空格剝離是字符串處理的一種基本操作,可以使用lstrip()方法(左)剝離前導(dǎo)空格,使用rstrip()(右)方法對(duì)尾隨空格進(jìn)行剝離,以及使用strip()剝離前導(dǎo)和尾隨空格。

s =  This is a sentence with whitespace. nprint(Strip leading

whitespace: {}.format(s.lstrip()))print(Strip trailing whitespace:

{}.format(s.rstrip()))print(Strip all whitespace: {}.format(s.strip()))

Strip leading whitespace: This is a sentence with whitespace.Strip trailing

whitespace: This is a sentence with whitespace.Strip all whitespace: This is a

sentence with whitespace.

對(duì)剝離除空格以外的字符感興趣嗎?同樣的方法也很有用,可以通過(guò)傳遞想要?jiǎng)冸x的字符來(lái)剝離字符。

s = This is a sentence with unwanted characters.AAAAAAAAprint(Strip

unwanted characters: {}.format(s.rstrip(A)))

Strip unwanted characters: This is a sentence with unwanted characters.

必要時(shí)不要忘記檢查字符串 format()文檔。

format()文檔:https://docs.python.org/3/library/stdtypes.html#str.format

二. 字符串拆分

利用Python中的 split() 方法可以輕易將字符串拆分成較小的子字符串列表。

split() 方法:https://docs.python.org/3/library/stdtypes.html#str.split

s = KDnuggets is a fantastic resourceprint(s.split())

[KDnuggets, is, a, fantastic, resource]

默認(rèn)情況下,split()根據(jù)空格進(jìn)行拆分,但同樣也可以將其他字符序列傳遞給split()進(jìn)行拆分。

s = these,words,are,separated,by,commaprint(, separated split ->

{}.format(s.split(,)))s = abacbdebfgbhhgbabddbaprint(b separated split

-> {}.format(s.split(b)))

, separated split -> [these, words, are, separated, by,

comma]b separated split -> [a, ac, de, fg, hhg, a, dd,

a]

3. 將列表元素合成字符串

需要實(shí)現(xiàn)上述操作的一個(gè)逆向操作?沒(méi)問(wèn)題,利用Python中的join()方法便可將列表中的元素合成一個(gè)字符串。

join()方法:https://docs.python.org/3/library/stdtypes.html#str.join

s = [KDnuggets, is, a, fantastic, resource]print( .join(s))

KDnuggets is a fantastic resource

事實(shí)果真如此!如果想將列表元素用空格以外的東西連接起來(lái)?這可能有點(diǎn)陌生,但也很容易實(shí)現(xiàn)。

s = [Eleven, Mike, Dustin, Lucas, Will]print( and .join(s))

Eleven and Mike and Dustin and Lucas and Will

4. 字符串反轉(zhuǎn)

Python沒(méi)有內(nèi)置的字符串反轉(zhuǎn)方法。但是,可以先將字符串看做是字符的列表,再利用反轉(zhuǎn)列表元素的方式進(jìn)行反轉(zhuǎn)。

5. 大小寫(xiě)轉(zhuǎn)換

利用upper(), lower(),和swapcase()方法可以進(jìn)行大小寫(xiě)之間的轉(zhuǎn)換。

upper()方法:https://docs.python.org/3/library/stdtypes.html#str.upperlower()方法:https://docs.python.org/3/library/stdtypes.html#str.lowerswapcase()方法:https://docs.python.org/3/library/stdtypes.html#str.swapcase

s = KDnuggetsprint(KDnuggets as uppercase:

{}.format(s.upper()))print(KDnuggets as lowercase:

{}.format(s.lower()))print(KDnuggets as swapped case:

{}.format(s.swapcase()))

KDnuggets as uppercase: KDNUGGETSKDnuggets as lowercase:

kdnuggetsKDnuggets as swapped case: kdNUGGETS

6. 檢查是否有字符串成員

在Python中檢查字符串成員的簡(jiǎn)單方法是使用in運(yùn)算符,語(yǔ)法與自然語(yǔ)言非常類(lèi)似。

s1 = perpendiculars2 = pens3 = pepprint(pen in perpendicular

-> {}.format(s2 in s1))print(pep in perpendicular ->

{}.format(s3 in s1))

pen in perpendicular -> Truepep in perpendicular -> False

如果對(duì)找到字符串中子字符串的位置更感興趣(而不是簡(jiǎn)單地檢查是否包含子字符串),則利用find()方法可能更為有效。

s = Does this string contain a substring?print(string location ->

{}.format(s.find(string)))print(spring location ->

{}.format(s.find(spring)))

string location -> 10spring location -> -1

    七、子字符串替換

找到子字符串之后,如果想替換這一子字符串,該怎么辦?Python 中的replace()字符串方法將解決這一問(wèn)題。

replace()字符串方法:https://docs.python.org/3/library/stdtypes.html#str.replace

s1 = The theory of data science is of the utmost importance.s2 =

practiceprint(The new sentence: {}.format(s1.replace(theory, s2)))

The new sentence: The practice of data science is of the utmost

importance.

如果同一個(gè)子字符串出現(xiàn)多次的話,利用計(jì)數(shù)參數(shù)這一選項(xiàng),可以指定要進(jìn)行連續(xù)替換的次數(shù)。

八、 組合多個(gè)列表的輸出

如何以某種元素的方式將多個(gè)字符串列表組合在一起?利用zip()函數(shù)便沒(méi)問(wèn)題。

zip()函數(shù):https://docs.python.org/3/library/functions.html#zip

countries = [USA, Canada, UK, Australia]cities = [Washington,

Ottawa, London, Canberra]for x, y in zip(countries, cities): print(The

capital of {} is {}..format(x, y))

The capital of USA is Washington.The capital of Canada is Ottawa.The

capital of UK is London.The capital of Australia is Canberra.

九、同字母異序詞檢查

想檢查一對(duì)字符串中,其中一個(gè)字符串是否是另一個(gè)字符串的同字母異序詞?從算法上來(lái)講,需要做的是對(duì)每個(gè)字符串中每個(gè)字母的出現(xiàn)次數(shù)進(jìn)行計(jì)數(shù),再檢查二者計(jì)數(shù)值是否相等,直接使用collections模塊的Counter類(lèi)便可實(shí)現(xiàn)。

collections模塊的Counter類(lèi):https://docs.python.org/3/library/collections.html#collections.Counter

from collections import Counterdef is_anagram(s1, s2): return Counter(s1)

== Counter(s2)s1 = listens2 = silents3 = runners4 =

neuronprint(listen is an anagram of silent ->

{}.format(is_anagram(s1, s2)))print(runner is an anagram of neuron

-> {}.format(is_anagram(s3, s4)))

listen an anagram of silent -> Truerunner an anagram of neuron

-> False

十、回文檢查

如果想檢查給定的單詞是否是回文,怎么辦?從算法上看,需要?jiǎng)?chuàng)建一個(gè)單詞的反轉(zhuǎn),然后利用 ==

運(yùn)算符來(lái)檢查這2個(gè)字符串(原始字符串和反向字符串)是否相等。

def is_palindrome(s): reverse = s[::-1] if (s == reverse): return True

return Falses1 = racecars2 = hippopotamusprint(racecar a palindrome

-> {}.format(is_palindrome(s1)))print(hippopotamus a palindrome ->

{}.format(is_palindrome(s2)))

racecar is a palindrome -> Truehippopotamus is a palindrome ->

False

雖然掌握這些字符串處理“技巧”之后,并不意味著你已經(jīng)成為了文本分析或自然語(yǔ)言處理專(zhuān)家,但這些技巧可能會(huì)激發(fā)出深入探究自然語(yǔ)言處理領(lǐng)域的興趣,并掌握終成為專(zhuān)家所必備的技能。

Python中的字符處理技巧你都了解嗎?如果說(shuō)想要學(xué)習(xí)python的話那么就來(lái)我們達(dá)內(nèi)科技的python培訓(xùn)班來(lái)學(xué)習(xí)吧,我們達(dá)內(nèi)科技?xì)g迎每位想要學(xué)習(xí)的學(xué)員來(lái)我們公司進(jìn)行實(shí)地考察,也可以點(diǎn)擊我們文章下面的獲取試聽(tīng)資格按鈕來(lái)獲取我們的python課程免費(fèi)試聽(tīng)資格,在試聽(tīng)中可以更加清楚的了解我們達(dá)內(nèi)科技。

電話咨詢

電話咨詢

咨詢電話:
4008-569-579
回到頂部

回到頂部