day5_python学习笔记_chapter6_字符串列表元组

1. 序列:seq[n], seq[x:y], seq * n序列重复n次,切片, 序列翻转 s=”abcde", s[::-1]="edcba"

  内建函数:1. 类型转换: list(iter), str(obj), unicode(obj), tuple(iter) , 2. len(seq), max(), min() , reversed(), sorted(), sum(),

------------------------------------------------------------------------------------------------------------------------------

2. 字符串: in ,not in ,,, import string , string.uppercase="ABCD....XYZ",  string.digits = '0123456789'

3. string.upper(str), str1.join(str): 用str1将字符串str连接起来, eg:'-'.join('abc') = 'a-b-c'

4. 字符串格式化操作符%, %c, %r, %s, %d, %f , %%(输入百分号)

5. 字符串模板:substitute, safe_substitute(), 前者更为严谨

   from string import Template

  s = Template('There are $(howmany} ${lang} ccc)

  print s.substitute(lang="python", howmany=3)

6. 原始字符串操作符(r/R)

7. 内建函数, enumerate(), zip(): 返回一个字符串列表 s='123', t='abc', zip(s, t), [('1', 'a'), ('2', 'b'), ('3', 'c')]

  raw_input(),

  string.capitalize(),将字符串第一个字符大写

  string.count(str, beg=0,end=len(string))返回str在字符串中出现的次数

  string.decode(encoding="UTF-8" errors='strict') 解码

  string.encode(encoding="utf-8" errors='strict') 编码

  string.endswith(obj, beg=0, end=len(string)) 检查字符串是否以obj结束,返回True,或False

  string.expandtabs(tabsize=8) 把字符串中的ab符号转换为空格

  string.find(str, beg=0, end=len(string)), string.index(str, beg, end)跟find()方法一样,只不过如果str不爱string中会报异常

  string.isalnum(), string是字符或者数字

  string.isalpha() string都是字母

  string.isdecimal()

  string.isdigit()

  string.islower()

  string.isnumeric()

  string.isspace() , 只包含空格返回true

  string.join(seq) ,用string将seq分割开来

  string.ljust 左对齐

  string. lower()

  string.lstrip() ,截掉string左边的空格

  string.partition(str), 从str第一次出现的地方, 将string分割成三部分

  string.replace(str1, str2, num), 把string中的str1替换为str2, 如果num制定,则替换不超过num次

  string.rfind(str, beg, end) ,从右边查找,string.rindex() 从右边查找 string.rpartition(str),

  string.startswith(obj,beg, end)

  string.swapcase(),翻转string中的大小写

  string.upper()

  string.split(str, num) ,以str分割string,不超过num次  'abcbe'.split('b', 2) = ['a','c','e']

  -----------------------------------------------------------------------------------------------------------------------------------------

8. 列表

  1. list.append(str), del list[1], in , not in , 连接操作符“+”    list1 + list2。 重复操作符 *, list1 * 2 

  2. 内建函数 len(), max(), min(), sorted(), reversed(),  enumerate(), zip(), sum(), list(), tuple()

    list.append(obj), list.count(obj),计算obj出现的次数, list.extend(seq),把序列seq的内容添加到list中, list.insert(index, obj),                              list.pop(index=-1), 删除并返回制定位置的对象,默认是最后一个对象,list.remove(obj), 从列表中删除对象obj,list.reverse(),

    原地翻转,list.sort(func=None, key=None, reverse=False) 

    sort() 无返回值,sorted(), reversed()有返回值。

  用列表模拟栈的操作:

  '''
Created on 2014-5-11
@author: jyp
'''
stack = []

def push():
    stack.append(raw_input("Enter new String: ").strip())
    
def pop():
    if len(stack) ==0:
        print "stack is null"
    else:
        print "Removed: [" ,`stack.pop()`, "]"
def veiwstack():
    print stack
CMDs = {'u': push, 'o': pop, 'v': veiwstack }

def showmenu():
    pr = """
    p(U)sh
    p(O)p
    (V)iew
    (Q)uit
    
    Enter your choice: """
    
    while True:
        while True:
            try:
                choice = raw_input(pr).strip()[0].lower()
            except (EOFError, KeyboardInterrupt, IndexError):
                choice = 'q'
            print ' You picked: %s' % choice
            if choice not in 'uovq':
                print 'invalid option, try agagin'
            else:
                break
        if choice == 'q':
            break
        CMDs[choice]()
if __name__ == '__main__':
    showmenu()

模拟队列操作:只需将上述代码中def pop() 函数中的,`stack.pop()` 改为:`stack.pop(0)`
--------------------------------------------------------------------------------------------------------------------------------------------

9. 拷贝对象, 深拷贝,浅拷贝,    浅拷贝相当于将对象的引用赋值给另一个对象, 并未拷贝这个对象,只是拷贝了对象的引用。

  浅拷贝: 1. 使用切片操作进行浅拷贝, 2. 使用工厂方法。

        eg: person= ['name', ['savings', 100]]

           hubby = person[:]  #通过切片操作[:]

           wifey = list(person)    #通过工厂函数实现浅拷贝

      2. 深拷贝: import copy      wifey = copy.deepcopy(person);

  


 

  

  

原文地址:https://www.cnblogs.com/yongpan666/p/3720264.html