Python入門:字符串處理

對於初學者來說,每種開發語言都有很多基礎性的東西要學,比如:數據類型(什麼是整數、什麼浮點數、什麼是字符串、什麼是列表、什麼是字典等),即使是學,大家也可能不知道爲什麼要學習,這和我成爲大神,啪啪啪寫出NB的遊戲、網站又有什麼關係,今天就給大家舉個栗子。

學習場景

有沒有這樣一個場景,你想登錄女票的某個APP賬號(騙人,程序員哪有女票),但是需要驗證碼,這個時候你又不能去女票的手機上直接看,那麼你就需要猜驗證碼,手工一個一個試?NO,這個時候你學習開發的好處就來了,你可用代碼生成所有可能的驗證碼,這樣就完成了第一步,然後再找一個破解工具加載生成的驗證碼錶一個個去試(當然破解工具你也可以自己寫啊),最終就可以試出來哪個驗證碼是正確的,這樣你就可以登錄女票的賬號了,是不是很興奮,是不是很開心。

有了場景,那麼我們先來學習第一步,生成驗證碼:

生成驗證碼

如果不是初學者請繞過
如果是初學者,下面的代碼看不懂也沒關係,這是讓你對開發有個認識,然後你所學的所有內容均是爲成寫出這樣的代碼做準備的,如:字符串處理等


import sys,getopt

def execDic(numLen):
    print("正在寫入……")
    # for i in range(int(str(1)+("0"*numLen))):
    #     if i/10 < 1:
    #         s = "0"*(numLen-1) + str(i)
    #         writeFile(numLen,s)
    #     elif 1 < i/10 < 10:
    #         s = "0"*(numLen-2) + str(i)
    #         writeFile(numLen,s)
    #     elif 1 < i/10 < 100:
    #         s = "0"*(numLen-3) + str(i)
    #         writeFile(numLen,s)
    #     elif 1 < i/10 < 1000:
    #         s = "0"*(numLen-4) + str(i)
    #         writeFile(numLen,s)
    #     elif 1 < i/10 < 10000:
    #         s = "0"*(numLen-5) + str(i)
    #         writeFile(numLen,s)
    #     elif 1 < i/10 < 100000:
    #         s = "0"*(numLen-6) + str(i)
    #         writeFile(numLen,s)
    for i in range(int("9"*int(numLen))+1):
        s = str(i).rjust(numLen,"0")
        writeFile(numLen,s)
    print("Done! OK!")
            
def writeFile(numLen,password):
    with open("password_"+str(numLen)+".txt","a") as f:
        f.write(password + "\n")


def _h():
    print("Usage: fullNum.py -h    --help")
    print("       fullNum.py -n 4, A num of length 4")
    #print("        fullNum.py 4,A num of length 4")


def main():
    argv = sys.argv[1:]
    if argv:
        try:
            opts,args = getopt.getopt(argv,"-h-n:",["help","num"])
        except getopt.GetoptError:
            _h()
            sys.exit()

        for opt,arg in opts:
            if opt in  ("-h","--help"):
                _h()
                sys.exit()
            elif opt in ("-n","--num"):
                try:
                    if 0 < int(arg) <= 6:
                        #print(int(arg))
                        execDic(int(arg))
                    else:
                        print("請輸入長度大於0小於等於6的數字!")
                except ValueError:
                    print("請輸入數字!")
    else:
        _h()
            
if __name__ == "__main__":
    main()

代碼運行結果,會得到如下長度爲3的所有驗證碼

D:\workspace\python\createPassword>python fullNum.py -n 3
正在寫入……
Done! OK!

000
...
096
097
098
099
100
101
102
...
999

代碼講解之字符串處理

  • str
    可以將非str的類型轉換成str(字符串)類型,之後就可以進行字符串的所有操作了,比如,字符串連接(拼接)、字符串分割等等
    如下例子假設你已經知道數字類型(整數類型)
In [15]: a = 1

In [16]: b = 2

In [17]: a + b
Out[17]: 3
In [18]: c = "1"

In [19]: a + c
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-e81e582b6fa9> in <module>
----> 1 a + c

TypeError: unsupported operand type(s) for +: 'int' and 'str'		
#這裏報錯了,電腦是不知道你想進行數字加法,還是字符串拼接,
#數字加法和字符串拼接都用+,所以需要將數字轉換成字符串,才能進行字符串拼接
In [20]: str(a) + c		# a是一個數字1,被轉換成字符串1
Out[20]: '11'
  • rjust
    在上例中,想把1變成3位的001,如果不知道rjust就需要像我上例中註釋掉的代碼一樣,先判斷數字的長度,如1的長度小於3那麼就給前面加兩個0,如22需要在前面加一個0,如果你知道rjust就可以直接使用如下代碼:
In [22]: c.rjust(3,"0")		# 括號中的3是在彌補的長度,"0"是表示用0作爲長度填充
Out[22]: '001'

現在你就可以實現批量生成驗證碼的功能了(除了循環100、1000個數字外等其它方法)MD,除了這麼大一堆🤣

當然字符串還有很多用法,應用於不同場景,所以再來看看字符串的一些其它用法。

擴展用法

  • ord用法
>>> ord
<built-in function ord>
>>> help(ord)
Help on built-in function ord in module __builtin__:

ord(...)
    ord(c) -> integer
    
    Return the integer ordinal of a one-character string.
>>> ord('a')
97
>>> ord('*')
42
>>> ord('+')
43
>>> ord('-')
45
>>> ord('=')
61
>>> ord('a')
97
>>> ord('aa')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
#返回一個按單一字符排順的整數
  • chr與ord相反
>>> chr(56)
'8'
  • 字符串截取
>>> a = 'abc'
>>> print(a[:])
abc
>>> print(a[:1])
a
>>> print(a[:3])
abc
>>> print(a[:4])
abc
>>> print(a[-1:])
c
>>> print(a[-2:])
bc

  • 字符串查找
>>> a.rfind('b')
1		# 找到返回位置
>>> a.rfind('c')
2		# 找到返回位置
>>> a.rfind('1')
-1		# 沒有找到返回-1
>>> a.rfind('19')
-1		# 沒有找到返回-1
>>> a = 'abc.txt'
>>> a.rfind('.')
3
>>> a[a.rfind('.')+1:]
'txt'
>>> a.find('e')
-1
>>> a.rfind('e')
-1
  • str.find & str.rfind
>>> help(a.rfind)
Help on built-in function rfind:

rfind(...)
    S.rfind(sub [,start [,end]]) -> int
    
    Return the highest index in S where substring sub is found,
    such that sub is contained within s[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.

>>> help(a.find)
Help on built-in function find:

find(...)
    S.find(sub [,start [,end]]) -> int
    
    Return the lowest index in S where substring sub is found,
    such that sub is contained within s[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.

>>> a.find('a')
0
>>> a.find('b')
1
>>> a.find('c')
2
>>> a.find('t')
4
>>> a.rfind('t')
6
  • str.index
>>> a.index('a')
0
>>> a.index('t')
4
>>> a.index('t')
4
>>> a.rindex('t')
6
>>> help(a.index)
Help on built-in function index:

index(...)
    S.index(sub [,start [,end]]) -> int
    
    Like S.find() but raise ValueError when the substring is not found.

>>> a.rindex('tt')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: substring not found
>>> a = 'aBccDE'
>>> a.capitalize()
'Abccde'
>>> a.lower()
'abccde'
>>> a.upper()
'ABCCDE'
>>> a.swapcase()
'AbCCde'
>>> a.title()
'Abccde'
>>> help(a.title())
problem in Abccde - <type 'exceptions.ImportError'>: No module named Abccde

>>> help(a.title)
Help on built-in function title:

title(...)
    S.title() -> string
    
    Return a titlecased version of S, i.e. words start with uppercase
    characters, all remaining cased characters have lowercase.

>>> help(a.capitalize)
Help on built-in function capitalize:

capitalize(...)
    S.capitalize() -> string
    
    Return a copy of the string S with only its first character
    capitalized.

>>> a.center(10)
'  aBccDE  '
>>> a.center(10,'!')
'!!aBccDE!!'
>>> help(a.center)
Help on built-in function center:

center(...)
    S.center(width[, fillchar]) -> string
    
    Return S centered in a string of length width. Padding is
    done using the specified fill character (default is a space)

>>> a.ljust(2)
'aBccDE'
>>> a.ljust(20)
'aBccDE              '		# 這裏有很多空格
>>> a.rjust(20)
'              aBccDE'
>>> print('{0}like{20}'.format('slg','python'))
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: tuple index out of range
>>> print('{0}like{1}'.format('slg','python'))
slglikepython
>>> print('{0} like {1}'.format('slg','python'))
slg like python
>>> print('{a} like {b}'.format(a='slg',b='python'))
slg like python
>>> url = 'www.baidu.com'
>>> s = url.partition('.')
>>> s
('www', '.', 'baidu.com')
>>> print s
('www', '.', 'baidu.com')
>>> print s[0]
www
>>> print s[1]
.
>>> print s[3]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: tuple index out of range
>>> print s[2]
baidu.com
>>> s = url.rpartition('.')
>>> s
('www.baidu', '.', 'com')
>>> s = 'www.baidu.com'
>>> s.replace('com','cn')
'www.baidu.cn'

>>> a = ''.maketrans('abcc','3008')
>>> a
{97: 51, 98: 48, 99: 56}
>>> print(a)
{97: 51, 98: 48, 99: 56}
>>> print('bbbbcccc'.translate(a))
00008888

同時建議初學都使用pychram等類似IDE工具,因爲在你輸入的過程中會有提示,會很好的幫助你理解當前的屬性、方法等
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章