1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        30個必備的Python字符串方法

        共 7876字,需瀏覽 16分鐘

         ·

        2022-06-24 17:12

        字符串是Python中基本的數(shù)據(jù)類型,幾乎在每個Python程序中都會使用到它。


        這次給大家介紹30個最重要的內(nèi)置字符串方法,希望大家能從中找到對自己有幫助的技巧。



        ▍1、Slicing


        slicing切片,按照一定條件從列表或者元組中取出部分元素(比如特定范圍、索引、分割值)


        s = '   hello   '
        s = s[:]

        print(s)
        #    hello


        s = '   hello   '
        s = s[3:8]

        print(s)
        # hello



        ▍2、strip()


        strip()方法用于移除字符串頭尾指定的字符(默認為空格或換行符)或字符序列。


        s = '   hello   '.strip()

        print(s)
        # hello


        s = '###hello###'.strip()

        print(s)
        # ###hello###


        在使用strip()方法時,默認去除空格或換行符,所以#號并沒有去除。


        可以給strip()方法添加指定字符,如下所示。


        s = '###hello###'.strip('#')

        print(s)
        # hello


        此外當(dāng)指定內(nèi)容不在頭尾處時,并不會被去除。


        s = ' \n \t hello\n'.strip('\n')

        print(s)
        #
        #      hello


        s = '\n \t hello\n'.strip('\n')

        print(s)
        #      hello


        第一個\n前有個空格,所以只會去取尾部的換行符。


        最后strip()方法的參數(shù)是剝離其值的所有組合,這個可以看下面這個案例。


        s = 'www.baidu.com'.strip('cmow.')

        print(s)
        # baidu


        最外層的首字符和尾字符參數(shù)值將從字符串中剝離。字符從前端移除,直到到達一個不包含在字符集中的字符串字符為止。


        在尾部也會發(fā)生類似的動作。



        ▍3、lstrip()


        移除字符左側(cè)指定的字符(默認為空格或換行符)或字符序列。


        s = '   hello   '.lstrip()

        print(s)
        # hello


        同樣的,可以移除左側(cè)所有包含在字符集中的字符串。


        s = 'Arthur: three!'.lstrip('Arthur: ')

        print(s)
        # ee!



        ▍4、rstrip()


        移除字符串右側(cè)指定的字符(默認為空格或換行符)或字符序列。


        s = '   hello   '.rstrip()

        print(s)
        #    hello



        ▍5、removeprefix()


        Python3.9中移除前綴的函數(shù)。


        # python 3.9
        s = 'Arthur: three!'.removeprefix('Arthur: ')

        print(s)
        # three!


        和strip()相比,并不會把集中的字符串進行逐個匹配。



        ▍6、removesuffix()


        Python3.9中移除后綴的函數(shù)。


        s = 'HelloPython'.removesuffix('Python')

        print(s)
        # Hello



        ▍7、replace()


        把字符串中的內(nèi)容替換成指定的內(nèi)容。


        s = 'string methods in python'.replace(' ''-')

        print(s)
        # string-methods-in-python


        s = 'string methods in python'.replace(' ''')

        print(s)
        # stringmethodsinpython



        ▍8、re.sub()


        re是正則的表達式,sub是substitute表示替換。


        re.sub則是相對復(fù)雜點的替換。


        import re
        s = "string    methods in python"
        s2 = s.replace(' ''-')
        print(s2)
        # string----methods-in-python


        s = "string    methods in python"
        s2 = re.sub("\s+""-", s)
        print(s2)
        # string-methods-in-python


        和replace()做對比,使用re.sub()進行替換操作,確實更高級點。



        ▍9、split()


        對字符串做分隔處理,最終的結(jié)果是一個列表。


        s = 'string methods in python'.split()

        print(s)
        # ['string', 'methods', 'in', 'python']


        當(dāng)不指定分隔符時,默認按空格分隔。


        s = 'string methods in python'.split(',')

        print(s)
        # ['string methods in python']


        此外,還可以指定字符串的分隔次數(shù)。


        s = 'string methods in python'.split(' ', maxsplit=1)

        print(s)
        # ['string', 'methods in python']


        ▍10、rsplit()


        從右側(cè)開始對字符串進行分隔。


        s = 'string methods in python'.rsplit(' ', maxsplit=1)

        print(s)
        # ['string methods in', 'python']



        ▍11、join()


        string.join(seq)。以string作為分隔符,將seq中所有的元素(的字符串表示)合并為一個新的字符串。


        list_of_strings = ['string''methods''in''python']
        s = '-'.join(list_of_strings)

        print(s)
        # string-methods-in-python


        list_of_strings = ['string''methods''in''python']
        s = ' '.join(list_of_strings)

        print(s)
        # string methods in python


        ▍12、upper()


        將字符串中的字母,全部轉(zhuǎn)換為大寫。


        s = 'simple is better than complex'.upper()

        print(s)
        # SIMPLE IS BETTER THAN COMPLEX



        ▍13、lower()


        將字符串中的字母,全部轉(zhuǎn)換為小寫。


        s = 'SIMPLE IS BETTER THAN COMPLEX'.lower()

        print(s)
        # simple is better than complex



        ▍14、capitalize()


        將字符串中的首個字母轉(zhuǎn)換為大寫。


        s = 'simple is better than complex'.capitalize()

        print(s)
        # Simple is better than complex



        ▍15、islower()


        判斷字符串中的所有字母是否都為小寫,是則返回True,否則返回False。


        print('SIMPLE IS BETTER THAN COMPLEX'.islower()) # False

        print('simple is better than complex'.islower()) # True



        ▍16、isupper()


        判斷字符串中的所有字母是否都為大寫,是則返回True,否則返回False。


        print('SIMPLE IS BETTER THAN COMPLEX'.isupper()) # True

        print('SIMPLE IS BETTER THAN complex'.isupper()) # False



        ▍17、isalpha()


        如果字符串至少有一個字符并且所有字符都是字母,則返回 True,否則返回 False。


        s = 'python'
        print(s.isalpha())
        # True

        s = '123'
        print(s.isalpha())
        # False

        s = 'python123'
        print(s.isalpha())
        # False

        s = 'python-123'
        print(s.isalpha())
        # False



        ▍18、isnumeric()


        如果字符串中只包含數(shù)字字符,則返回 True,否則返回 False。


        s = 'python'
        print(s.isnumeric())
        # False

        s = '123'
        print(s.isnumeric())
        # True

        s = 'python123'
        print(s.isnumeric())
        # False

        s = 'python-123'
        print(s.isnumeric())
        # False



        ▍19、isalnum()


        如果字符串中至少有一個字符并且所有字符都是字母或數(shù)字,則返回True,否則返回 False。


        s = 'python'
        print(s.isalnum())
        # True

        s = '123'
        print(s.isalnum())
        # True

        s = 'python123'
        print(s.isalnum())
        # True

        s = 'python-123'
        print(s.isalnum())
        # False



        ▍20、count()


        返回指定內(nèi)容在字符串中出現(xiàn)的次數(shù)。


        n = 'hello world'.count('o')
        print(n)
        # 2

        n = 'hello world'.count('oo')
        print(n)
        # 0



        ▍21、find()


        檢測指定內(nèi)容是否包含在字符串中,如果是返回開始的索引值,否則返回-1。


        s = 'Machine Learning'
        idx = s.find('a')

        print(idx)
        print(s[idx:])
        # 1
        # achine Learning

        s = 'Machine Learning'
        idx = s.find('aa')

        print(idx)
        print(s[idx:])
        # -1
        # g


        此外,還可以指定開始的范圍。


        s = 'Machine Learning'
        idx = s.find('a'2)

        print(idx)
        print(s[idx:])
        # 10
        # arning



        ▍22、rfind()


        類似于find()函數(shù),返回字符串最后一次出現(xiàn)的位置,如果沒有匹配項則返回 -1。


        s = 'Machine Learning'
        idx = s.rfind('a')

        print(idx)
        print(s[idx:])
        # 10
        # arning



        ▍23、startswith()


        檢查字符串是否是以指定內(nèi)容開頭,是則返回 True,否則返回 False。


        print('Patrick'.startswith('P'))

        # True



        ▍24、endswith()


        檢查字符串是否是以指定內(nèi)容結(jié)束,是則返回 True,否則返回 False。


        print('Patrick'.endswith('ck'))

        # True



        ▍25、partition()


        string.partition(str),有點像find()和split()的結(jié)合體。


        從str出現(xiàn)的第一個位置起,把字符串string分成一個3 元素的元組(string_pre_str,str,string_post_str),如果string中不包含str則 string_pre_str==string。


        s = 'Python is awesome!'
        parts = s.partition('is')
        print(parts)
        # ('Python ', 'is', ' awesome!')

        s = 'Python is awesome!'
        parts = s.partition('was')
        print(parts)
        # ('Python is awesome!', '', '')



        ▍26、center()


        返回一個原字符串居中,并使用空格填充至長度width的新字符串。


        s = 'Python is awesome!'
        s = s.center(30'-')

        print(s)
        # ------Python is awesome!------



        ▍27、ljust()


        返回一個原字符串左對齊,并使用空格填充至長度width的新字符串。


        s = 'Python is awesome!'
        s = s.ljust(30'-')

        print(s)
        # Python is awesome!------------



        ▍28、rjust()


        返回一個原字符串右對齊,并使用空格填充至長度width的新字符串。


        s = 'Python is awesome!'
        s = s.rjust(30'-')

        print(s)
        # ------------Python is awesome!



        ▍29、f-Strings


        f-string是格式化字符串的新語法。


        與其他格式化方式相比,它們不僅更易讀,更簡潔,不易出錯,而且速度更快!


        num = 1
        language = 'Python'
        s = f'{language} is the number {num} in programming!'

        print(s)
        # Python is the number 1 in programming!


        num = 1
        language = 'Python'
        s = f'{language} is the number {num*8} in programming!'

        print(s)
        # Python is the number 8 in programming!



        ▍30、swapcase()


        翻轉(zhuǎn)字符串中的字母大小寫。


        s = 'HELLO world'
        s = s.swapcase()

        print(s)
        # hello WORLD


        加入知識星球【我們談?wù)摂?shù)據(jù)科學(xué)】

        500+小伙伴一起學(xué)習(xí)!








        · 推薦閱讀 ·

        盤點2021最佳數(shù)據(jù)可視化作品

        一行代碼實現(xiàn)地址信息解析

        新一代Python包管理工具來了


        瀏覽 50
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            丰满的少妇被猛烈进入白浆91 | 国产夫妻做爱视频 | av天堂首页 | 男人插女人40分钟 | 性爱无码视频 | 电家庭影院午夜29332 | 骚虎视频www网站 | 奇米成人电影 | 靡伦理.游戏达人 | 女人扒开双腿让男人桶 |