1. gzyueqian
      13352868059

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

      更新時間: 2020-08-14 16:14:44來源: 粵嵌教育瀏覽量:9334

          Python是一門非常流行的開發語言了,python現在會這么的收歡迎不止是因為人工智能的帶動,有很大的一部分是因為它是比較簡單易學的,但是在使用python的時候有很多的字符的處理技巧你知道嗎?這些處理技巧可以讓你的工作更加的便捷。

        1. 空格剝離


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


        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.


        對剝離除空格以外的字符感興趣嗎?同樣的方法也很有用,可以通過傳遞想要剝離的字符來剝離字符。


        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.


        必要時不要忘記檢查字符串 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']


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


        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. 將列表元素合成字符串


        需要實現上述操作的一個逆向操作?沒問題,利用Python中的join()方法便可將列表中的元素合成一個字符串。

        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


        事實果真如此!如果想將列表元素用空格以外的東西連接起來?這可能有點陌生,但也很容易實現。


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


        Eleven and Mike and Dustin and Lucas and Will


        4. 字符串反轉


        Python沒有內置的字符串反轉方法。但是,可以先將字符串看做是字符的列表,再利用反轉列表元素的方式進行反轉。


        5. 大小寫轉換


        利用upper(), lower(),和swapcase()方法可以進行大小寫之間的轉換。


        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中檢查字符串成員的簡單方法是使用in運算符,語法與自然語言非常類似。


        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


        如果對找到字符串中子字符串的位置更感興趣(而不是簡單地檢查是否包含子字符串),則利用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.


        如果同一個子字符串出現多次的話,利用計數參數這一選項,可以指定要進行連續替換的次數。


        8. 組合多個列表的輸出


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


        zip()函數: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. 同字母異序詞檢查


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


        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. 回文檢查


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


        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


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


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

      免費預約試聽課

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

      
      

      1. 亚洲欧美中文高清在线专区 | 亚洲人成网站a在线播放 | 日本中文一区二区三区亚洲 | 亚洲国内自拍欧美一区二区三区 | 亚洲成色最大综合在线 | 在线观看AV永久免费网址 |