python 學習筆記day04-python字符串、列表、元組

字符串

    序列

        序列類型操作符

序列操作符
作用
seq[ind]
獲得下標爲ind的元素
seq[ind1:ind2]
獲得下標從ind1到ind2間的元素結合
seq * expr
序列重複expr次
seq1 + seq2
連接序列seq1和seq2
obj in seq
判斷obj元素是否包含在seq中
obj not in seq
判斷obj元素是否不包含在seq中

        內建函數

函數
含義
list(iter)
把可迭代對象轉換爲列表
str(obj)
把obj對象轉換成字符串
tuple(iter)
把一個可迭代對象轉換成一個元組對象

             >>> list('hello')
                ['h', 'e', 'l', 'l', 'o']
                >>> list(['hello','world'])
                ['hello', 'world']
                >>> str(['hello,','world'])
                "['hello,', 'world']"

        len(seq):返回seq的長度

        max(iter,key=None):返回iter中的最大值

            >>> max('abf')
            'f'
            >>> ord('a')
            97
            >>> ord('f')
            102
            >>> max([10,234,3421,12])
            3421

        enumerate:接受一個可迭代對象作爲參數,返回一個enumerate對象

                >>> for i,j in enumerate(aList):
                ...   print "index %d:%s" %(i,j)
                ...
                index 0:hello
                index 1:world

        reversed(seq):接受一個序列作爲參數,返回一個以逆序訪問的迭代器

        sorted(iter):接受一個可迭代對象作爲參數,返回一個有序的列表

            >>> aList = [32,43,323,55]
            >>> sorted(aList)
            [32, 43, 55, 323]
            >>> for item in reversed(aList):
            ...  print item
            ...
            55
            323
            43
            32

    字符串

        字符串操作符

            比較操作符:字符串大小按ASCII碼值大小進行比較

            切片操作符:[]、[:]、[::]

            成員關係操作符:in、not in

                >>> pyStr = 'Hello World!'
                >>> pyStr[::2]
                'HloWrd'
                >>> pyStr[::-1]
                '!dlroW olleH'

小練習:

    檢查標識符

    1、程序接受用戶輸入

    3、判斷用戶輸入的標識符是否合法

        #!/usr/bin/env python

        import string

        first_chs = string.letters + '_'
        other_chs = first_chs + string.digits
        def check_id(myid):
            if myid[0] not in first_chs:
                print "1st char invalid."
                return
            for ind,ch in enumerate(myid[1:]):
                if ch not in other_chs:
                    print "char in position: %s invalid" %(ind + 2)
                    break
            else:
                print "%s is valid" % myid
        if __name__ == '__main__':
            myid = raw_input("id to check: ")
                if myid:
                    check_id(myid)
                else:
                    print "You must input an identifier."

        格式化操作符

            字符串可以使用格式化符號來表示特定含義

格式化字符
轉換方式
%c
轉換成字符
%s
優先用str()函數進行字符串轉換
%d/%i
轉成有符號十進制數
%o

轉成無符號八進制數

%e/%E
轉成科學計數法
%f/%F
轉成浮點數

        >>> "%o" % 10
        '12'
        >>> "%#o" % 10
        '012'
        >>> "%#x" % 10
        '0xa'
        >>> "%e" % 1000000
        '1.000000e+06'

        >>> "%f" % 3.1415
        '3.141500'
        >>> "%4.2f" % 3.1415
        '3.14'

格式化操作符輔助指令
作用
*

定義寬度或小數點精度

(>>> "%*s%*s" % (-8,'name',-5,'age')

'name    age  '

-
左對齊
+
在正數前面顯示加號
<sp>
在正數前面顯示空格
#

在八進制數前面顯示0,在十六進制數前面顯示‘0

x’或者‘0X ’

0
顯示的數字前面填充0而不是默認的空格

        >>> "my ip is: %s" % '192.168.1.1'
        'my ip is: 192.168.1.1'
        >>> "my ip is: {}".format('192.168.1.1')
        'my ip is: 192.168.1.1'
        >>> "my ip is:{},you ip is: {}".format('192.1268.1.1','172.40.1.1')
        'my ip is:192.1268.1.1,you ip is: 172.40.1.1'
        >>> "my ip is:{1},you ip is: {0}".format('192.1268.1.1','172.40.1.1')
        'my ip is:172.40.1.1,you ip is: 192.1268.1.1'
小練習

1、提示用戶輸入(多行)數據

2、假定屏幕寬度爲50,用戶輸入的多行數據顯示(文本內容居中):

+********************************+

+                hello world                              +

+                great work!                              +

+********************************+
#!/usr/bin/env python

def get_contents():
    contents = []
    while True:
        data = raw_input("(Enter to quit)> ")
        if not data:
            break
        contents.append(data)
    return contents

if __name__ == '__main__':
    width = 48
    lines = get_contents()
    print'+%s+' %('*' * width)
    for line in lines:
        sp_wid,extra = divmod((width - len(line)),2)
        print "+%s%s%s+" %(' ' * sp_wid,line,' ' * (sp_wid + extra))
    print'+%s+' % ('*' * width)

        字符串模板

            string 模板提供了一個Template對象,利用該對象可以實現字符串模板的功能

                >>> import tab
                >>> import string
                >>> origTxt = "Hi ${name}, I will see you ${day}"
                >>> t = string.Template(origTxt)
                >>> t.substitute(name = 'bob',day = 'tomorrow')
                'Hi bob, I will see you tomorrow'
                >>> t.substitute(name = 'tom',day = 'the day after tommorrow')
                'Hi tom, I will see you the day after tommorrow'

小練習

創建用戶

    1、編寫一個程序,實現創建用戶的功能

    2、提示用戶輸入用戶名

    3、隨機生成8位密碼

    4、創建用戶並設置密碼

    5、發郵件通知用戶相關信息

#!/usr/bin/env python

import sys
import os
import randpass2
import string

contents  = '''username:  ${username}
password: ${password}
'''

t = string.Template(contents)

def adduser(user,  passwd,  email):
    os.system("useradd %s" %user)
    os.system("echo %s:%s | chpasswd" %(passwd,user))
    #os.system("echo %s | passwd --stdin %s" %(passwd,user))
    data = t.substitute(username=user,password = passwd)
    os.system("echo -e '%s' | mail -s 'user info' %s" %(data,email))
if __name__ == '__main__':
    username = sys.argv[1]
    pwd = randpass2.gen_pass()
    adduser(username,pwd,"root@localhost")

        原始字符串操作符

            原始字符串操作符是爲了對付那些在字符串中出現的特殊字符

            在原始字符串裏,所有的的字符都是直接按照字面的意思來使用,沒有轉義特殊或不能打印的字符

                >>> winPath = "c:\windows\temp"
                >>> winPath
                'c:\\windows\temp'
                >>> import tab
                >>> print winPath
                c:\windows    emp
                >>> newPath = r"c:\windows\temp"
                >>> newPath
                'c:\\windows\\temp'
                 >>> print newPath
                c:\windows\temp

        內建函數

            string.cpaitalize():把字符串的第一個字符大寫

                >>> 'hello world!'.capitalize()
                'Hello world!'

            string.center(width):返回一個原字符串居中,並使用空格填充至長度width的新字符串

                >>> print '|'+ 'hello world!'.center(20)+ '|'
                |    hello world!    |

            >>> hi = "hello wolrd"

                >>> hi.center(20,'+')
                '++++hello wolrd+++++'
                >>> hi.ljust(20,'+')
                'hello wolrd+++++++++'
                >>> hi.rjust(20,'+')
                '+++++++++hello wolrd'

            string.count(str,beg=0,end=len(string)):返回str在string裏面出現的次數,如果beg或者end指定則返回指定範圍內str出現的次數

                >>> hi = "hello wolrd"

                >>> hi.count("l")

                3

            string.endswith(obj,beg=0,end=len(string)):檢查字符串是否以obj結束,如果beg或者end指定檢查指定範圍內是否以obj結束,如果是,返回True,否則返回False

                >>> hi.endswith("d") 是 以d結尾?
                True
                >>> hi.startswith("hello")  是以hello 開始?
                True

             >>> '12'.isdigit()  是數字
                True

                >>> hi.islower() 是小寫
                True

                >>> hi.isupper()  是大寫?
                False

                >>> hi.isalpha()
                False
                >>> "hello".isalpha()
                True
                >>> "hello123".isalpha()是不是字母
                False

                >>> "hello123".isalnum()是不是字母數字組合
                True
            string.strip():刪除string字符串兩端的(空白)

            strint.upper():轉換string中的小寫字母爲大寫

                    >>> hi = 'hello wolrd!'
                    >>> hi.strip('!')
                    'hello wolrd'

                    >>> "\t hello world\n".strip()
                    'hello world'
                    >>> "\t hello world\n".lstrip()
                    'hello world\n'
                    >>> "\t hello world\n".rstrip()
                    '\t hello world'
                    >>> 'hello'.upper()
                    'HELLO'
                    >>> 'hello'.lower()
                    'hello'

            string.split(str="",num = string.count(str)):以str爲分隔符切片string,如果num有指定值,則僅分隔num個字符串

                    >>> 'mytest.tar.gz'.split('.')
                    ['mytest', 'tar', 'gz']

                    >>> testStr = ''' hello everyone.
                    ... welcome to python.
                    ... it is a great language.'''
                    >>> testStr
                    ' hello everyone.\nwelcome to python.\nit is a great language.'
                    >>> print testStr
                     hello everyone.
                    welcome to python.
                    it is a great language.
                    >>> testStr.splitlines()
                    [' hello everyone.', 'welcome to python.', 'it is a great language.']
                    >>>
                    >>> mylist = ['mytest', 'tar', 'gz']
                    >>> '.'.join(mylist) #拼接
                    'mytest.tar.gz'

                    >>> '/'.join(mylist)
                    'mytest/tar/gz'
                    >>> hi
                    'hello wolrd!'
                    >>> hi.replace('l','a')
                    'heaao woard!'
                    >>> hi.replace('l','a',2)
                    'heaao wolrd!'
列表

    列表基礎操作

        創建及訪問列表

            列表是有序、可變的數據類型

            列表中可以包含不同類型的對象

            列表可以有[]或工廠函數創建

            支持下標及切片操作

                >>> aList = [1,2,'hello']
                >>> bList = list('new')
                >>> print aList
                [1, 2, 'hello']
                >>> print bList
                ['n', 'e', 'w']

        更新列表

            通過下標只能更新值,不能使用下標添加新值

                >>> alist = [10,20]
                >>> alist[0] = 1
                >>> alist
                [1, 20]

                >>> alist[2]=30
                Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                IndexError: list assignment index out of range
                >>> alist = [10,20,30,40]
                >>> alist[1:3]
                [20, 30]
                >>> alist[1:3] = [2,3]
                >>> alist
                [10, 2, 3, 40]

                >>> alist[1:3] = [20,30,35]
                >>> alist
                [10, 20, 30, 35, 40]

                >>> alist[2:2] = [22,24,26,28]
                >>> alist
                [10, 20, 22, 24, 26, 28, 30, 35, 40]

            可以使用append方法追加新值

        刪除列表

            可以使用del刪除列表項或整個列表

            刪除列表項還可以使用pop()及remove()方法

                >>> aList = ['hello','world','new','list','name']
                >>> aList.pop() #彈出列表中最後一個值(默認下標爲-1),下標可在()中顯示標出
                'name'
                >>> aList
                ['hello', 'world', 'new', 'list']
                >>> del aList[2]
                >>> aList
                ['hello', 'world', 'list']
                >>> aList.remove('list') #刪除指定元素,非下標,若有多個,則只刪除第一個
                >>> aList
                ['hello', 'world']
                >>> del aList
                >>> print aList
                Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                NameError: name 'aList' is not defined

    列表操作進階

        列表操作符

            由於列表也是序列裏誒型,所以+、*、in、not in都適用與列表,但是需要注意參與運算的對象屬於同一類型

                >>> ['hello','world'] * 2
                ['hello', 'world', 'hello', 'world']
                >>> ['hello','world'] + 'new'
                Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                TypeError: can only concatenate list (not "str") to list
                >>> ['hello','world'] + ['new']
                ['hello', 'world', 'new']

        作用於列表的函數

            與字符串類似,列表也支持如下函數:

                - len()

                - max()

                - min()

                - sorted()

                - enumerate()

                - sum()

                - zip()

        列表內建函數

列表方法
操作
list.append(obj)
向列表中添加一個對象obj
list.count(obj)
返回一個對象obj在列表中出現的次數
list.extend(seq)
把序列seq的內容添加到列表中
list.index(obj)
返回obj對象的下標
list.insert(index,obj)
在索引量爲index的位置插入對象obj
list.reverse()
原地翻轉列表
list.sort()
排序

            >>> alist
            [10, 20, 22, 24, 26, 28, 30, 35, 40]
            >>> alist.append('hi')
            >>> alist
            [10, 20, 22, 24, 26, 28, 30, 35, 40, 'hi']
            >>> alist.extend('hi')
            >>> alist
            [10, 20, 22, 24, 26, 28, 30, 35, 40, 'hi', 'h', 'i']

            >>> alist.extend(['hello','world'])
            >>> alist
            [10, 20, 22, 24, 26, 28, 30, 35, 40, 'hi', 'h', 'i', 'hello', 'world']

            >>> alist[-5:]
            ['hi', 'h', 'i', 'hello', 'world']
            >>> alist[-5:] = []
            >>> alist
            [10, 20, 22, 24, 26, 28, 30, 35, 40]
            >>> alist.index(24)
            3
            >>> alist.insert(3,30)
            >>> alist
            [10, 20, 22, 30, 24, 26, 28, 30, 35, 40]
            >>> alist.reverse()
            >>> alist
            [40, 35, 30, 28, 26, 24, 30, 22, 20, 10]
            >>> alist.sort()
            >>> alist
            [10, 20, 22, 24, 26, 28, 30, 30, 35, 40]
            >>> import random
            >>> random.shuffle(alist) # 將alist 列表順序打亂
            >>> alist
            [30, 20, 30, 22, 26, 35, 28, 10, 40, 24]



小練習(答案見評論)

1、棧是一個後進先出的結構

2、編寫一個程序,用列表實現棧結構

3、需要支持壓棧、出棧、查詢功能


元組

    元組基礎

        創建元組

            通過()或工廠函數tuple()創建元組

            元組是有序的、不可變類型

            與列表類似,作用於列表的操作,絕大多數也可以作用於元組

                >>> aTuple = ('one','two','Three')
                >>> bTuple = tuple(['hello','world'])
                >>> print aTuple
                ('one', 'two', 'Three')
                >>> print bTuple
                ('hello', 'world')

        元組操作符

            由於元組也是序列類型、所以作用在序列上的操作都可以用於元組

            通過in、not in 判斷成員關係

                >>> print bTuple
                ('hello', 'world')
                >>> 'hello' in bTuple
                True


    元組特性

        單元素元組

            如果一個元組中只有一個元素,那麼創建該元素的時候需要加上一個逗號

                >>> cTuple = ("hello")
                >>> print cTuple
                hello
                >>> type(cTuple)
                <type 'str'>
                >>> dTuple = ('hello',)
                >>> print dTuple
                ('hello',)
                >>> type(dTuple)
                 <type 'tuple'>

        “更新”元組

            雖然元組本身是不可變的,但是因爲它同時屬於容器類型,也就意味着元組的某一個元素是可變的容器類型,那麼這個元素中的項目仍然可變

            >>> aTuple = ('bob',['[email protected]','beijing'])
            >>> print aTuple
            ('bob', ['[email protected]', 'beijing'])
            >>> aTuple[0] = 'tom'
            Traceback (most recent call last):
              File "<stdin>", line 1, in <module>
            TypeError: 'tuple' object does not support item assignment
            >>> aTuple[1][1] = 'shanghai'
            >>> print aTuple
            ('bob', ['[email protected]', 'shanghai'])

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