1. gzyueqian
      13352868059

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

      更新時(shí)間: 2020-08-14 16:14:44來源: 粵嵌教育瀏覽量:9296

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

        1. 空格剝離


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


        s = ' This is a sentence with whitespace. n'print('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ì)剝離除空格以外的字符感興趣嗎?同樣的方法也很有用,可以通過傳遞想要?jiǎng)冸x的字符來剝離字符。


        s = 'This is a sentence with unwanted characters.AAAAAAAA'print('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


        2. 字符串拆分


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


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


        s = 'KDnuggets is a fantastic resource'print(s.split())


        ['KDnuggets', 'is', 'a', 'fantastic', 'resource']


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


        s = 'these,words,are,separated,by,comma'print('',' separated split -> {}'.format(s.split(',')))s = 'abacbdebfgbhhgbabddba'print(''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è)逆向操作?沒問題,利用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í)果真如此!如果想將列表元素用空格以外的東西連接起來?這可能有點(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沒有內(nèi)置的字符串反轉(zhuǎn)方法。但是,可以先將字符串看做是字符的列表,再利用反轉(zhuǎn)列表元素的方式進(jìn)行反轉(zhuǎn)。


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


        利用upper(), lower(),和swapcase()方法可以進(jìn)行大小寫之間的轉(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 = 'KDnuggets'print(''KDnuggets' as uppercase: {}'.format(s.upper()))print(''KDnuggets' as lowercase: {}'.format(s.lower()))print(''KDnuggets' as swapped case: {}'.format(s.swapcase()))


        'KDnuggets' as uppercase: KDNUGGETS'KDnuggets' as lowercase: kdnuggets'KDnuggets' as swapped case: kdNUGGETS


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


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


        s1 = 'perpendicular's2 = 'pen's3 = 'pep'print(''pen' in 'perpendicular' -> {}'.format(s2 in s1))print(''pep' in 'perpendicular' -> {}'.format(s3 in s1))


        'pen' in 'perpendicular' -> True'pep' 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 -> 10'spring' location -> -1


        7. 子字符串替換


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


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


        s1 = 'The theory of data science is of the utmost importance.'s2 = 'practice'print('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ù)。


        8. 組合多個(gè)列表的輸出


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


        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.


        9. 同字母異序詞檢查


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


        collections模塊的Counter類:https://docs.python.org/3/library/collections.html#collections.Counter


        from collections import Counterdef is_anagram(s1, s2): return Counter(s1) == Counter(s2)s1 = 'listen's2 = 'silent's3 = 'runner's4 = 'neuron'print(''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' -> True'runner' an anagram of 'neuron' -> False


        10. 回文檢查


        如果想檢查給定的單詞是否是回文,怎么辦?從算法上看,需要?jiǎng)?chuàng)建一個(gè)單詞的反轉(zhuǎn),然后利用 == 運(yùn)算符來檢查這2個(gè)字符串(原始字符串和反向字符串)是否相等。


        def is_palindrome(s): reverse = s[::-1] if (s == reverse): return True return Falses1 = 'racecar's2 = 'hippopotamus'print(''racecar' a palindrome -> {}'.format(is_palindrome(s1)))print(''hippopotamus' a palindrome -> {}'.format(is_palindrome(s2)))


        'racecar' is a palindrome -> True'hippopotamus' is a palindrome -> False


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


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

      免費(fèi)預(yù)約試聽課

      亚洲另类欧美综合久久图片区_亚洲中文字幕日产无码2020_欧美日本一区二区三区桃色视频_亚洲AⅤ天堂一区二区三区

      
      

      1. 日本野花视频在线看免费 | 亚洲va韩国va欧美va久久 | 日本久久A级推油电影 | 亚洲国产一区二区三区网站 | 久久99精品久久不卡 | 亚洲欧美国产一区二区 |