pyton 字符串、list

python 字符串

  1. 连接字符串

"abc" + "def"
'abcdef'
>>> s1="abc"
>>> s2="def"
>>> s3=s1 + s2
>>> print s3
abcdef


       2. 占位符:python 规定了一些占位符,通过这些占位符来说明那个位置应该填写些什么类型的数据

%d   ---->整数       %s   ---->字符串

>>> a=100
>>> print "This is %d" % a   #%  是分隔符,后面的是具体的数据(可以是变量)
This is 100
>>> s="My name is cao"
>>> print "This is %s" % s
This is My name is cao

      3. 用占位符来连接字符串

>>> a="py"
>>> b="thon"
>>> print "%s%s" % a,b
Traceback (most recent call last):
  File "", line 1, in ?

>>> print "%s%s" %(a,b)  #如果有多个占位符,那需要把后面的复制数据用() 括起来
python

      4. len(object) 来获取字符串的字符个数

str="abcdefg"
>>> len(str)
7

      5. 字符串的大小写

>>> str.lower()
'abcdefg'
>>> str.upper()
'ABCDEFG'
>>> str
'abcdefg'      #但是原来的字符串str 是不会改变的

s="this is cao,nice to meet you"
>>> s.title()
'This Is Cao,Nice To Meet You'   #每个单词的首字母大写

>>> s1=s.title()
>>> print s1
This Is Cao,Nice To Meet You
>>> s.istitle()    #判断是否每个单词首字母都是大写
False
>>> s1.istitle()
True

   6. 字符串的位置:

str="abcdefg"
str[0]="a"
str[1]="b"

>>> str[2:4]
'cd'  #字符串的截取

   7. 字符串去掉左、右两侧的空格

>>> str=" abc defg " 
>>> str.lstrip()
'abc defg '
>>> str.rstrip()
' abc defg'
>>> str.strip() 
'abc defg'

python list

1. list里面的数据可以是int string bool 值

用help(list) 查看list所有操作,如果不是很确定可以用一个例子来验证下:

注意:下面所有的方法都会改变原来的list   list.reverse()

append(...)
 |      L.append(object) -- append object to end  #list后面append 一个元素
 |  
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value  #list中value的个数
 |  
 |  extend(...)
 |      L.extend(iterable) -- extend list by appending elements from the iterable  #把iterable的list 扩充到L的后面,其实就是2个list的合并
 |  
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value  #返回value第一次出现的index(索引)
 |  
 |  insert(...)
 |      L.insert(index, object) -- insert object before index #在index 之前插入value
 |  
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last)#删除并返回item  l.pop() 删除最后一个item 并返回item
 |  
 |  remove(...)
 |      L.remove(value) -- remove first occurrence of value  #删除第一次出现的value
 |  
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*  #list 进行反序
>>> print li
['cao', 'test', 'abc', 'shuming', 6, 1]
>>> li.reverse()
>>> print li
[1, 6, 'shuming', 'abc', 'test', 'cao']
 |  
 |  sort(...)
 |      L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;  #排序
 |      cmp(x, y) -> -1, 0, 1

    2. range()内置函数生成一个int型的list

help(range) 
Help on built-in function range in module __builtin__:

range(...)
    range([start,] stop[, step]) -> list of integers    #产生一个int 型的list  start 开始的int stop是结束的整型,step 是差值  类是一个等差数列
                                                        #start 默认是0   step  默认是1 stop是比填写的
    Return a list containing an arithmetic progression of integers.
    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
    When step is given, it specifies the increment (or decrement).
    For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
    These are exactly the valid indices for a list of 4 elements.

li=range(5)
>>> print li
[0, 1, 2, 3, 4]
>>> li=range(1,5)
>>> print li
[1, 2, 3, 4]
>>> li=range(1,10,2)
>>> print li
[1, 3, 5, 7, 9]
>>> li=range(10,2)  
>>> print li
[]
>>> li=range(0,10,2)
>>> print li
[0, 2, 4, 6, 8]

>>> for i in range(5):print "This is %s" %(i)  #range 跟for 循环是一样的
... 
This is 0
This is 1
This is 2
This is 3
This is 4

li=[i**2 for i in range(1,10)]    #list 简单的循环使用方式
>>> print li
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> range(-9)
[]
>>> range(-9,-1)
[-9, -8, -7, -6, -5, -4, -3, -2]
>>> range(,-3-9,-1)
  File "", line 1
    range(,-3-9,-1)
          ^
SyntaxError: invalid syntax
>>> range(-3,-9,-1) 
[-3, -4, -5, -6, -7, -8] 

   3.  另外一个重要的内置函数  enumerate()  # 列举 枚举的意思

class enumerate(object)
 |  enumerate(iterable) -> iterator for index, value of iterable
 |  
 |  Return an enumerate object.  iterable must be an other object that supports
 |  iteration.  The enumerate object yields pairs containing a count (from
 |  zero) and a value yielded by the iterable argument.  enumerate is useful
 |  for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ...  #可以认为是把list 改成了dict

>>> print name
['my', 'name', 'is', 'cao']
>>> li=list(enumerate(name))
>>> print li
[(0, 'my'), (1, 'name'), (2, 'is'), (3, 'cao')]


list 和str的转换:

1. str 上面所有的 函数都是不改变原来的str,调用str的函数后会得到一个新的str;

    list恰好相反,list调用相关的函数后不把原来的list 改变。

2. str 改成list ---->split()函数

split(...)
    S.split([sep [,maxsplit]]) -> list of strings
    
    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator.
(END) 

#sep 就是delimiter 分界符的意思,maxsplit:最大的分隔(以sep为分隔符,前maxsplit的sep 进行分分隔,后面的不再分割)
 str=" bcd   def:ghk:1234:eefff"
>>> str.split(":",2)
[' bcd   def', 'ghk', '1234:eefff'] #只分了2个,后面的: 不再分隔

str.split(1)              #maxsplit 必须跟sep 配合使用,否则会报错
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: expected a character buffer object
>>> 

3. 把list 修改为string   -->"sep".join(list)

li=["1","3","abc","def"]
>>> ",".join(li)  #用,作为链接符
'1,3,abc,def'
>>> "".join(li) 
'13abcdef'

>>> li=[1,2,"adc","def"]   #把list 修改为string时,注意list里面不能有非string类型的数据
>>> ",".join(li)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: sequence item 0: expected string, int found

4. list 和str 的数据类型不同:

  string 必须放在'' "" ''' ''' 里面里面的必须是字符,但是list里面的数据可以是任何数据:比如 int string list tupe 。。。。

li=[[1,2,"abc"],["def",34,(10,"aef")]]
>>> print li
[[1, 2, 'abc'], ['def', 34, (10, 'aef')]]



你可能感兴趣的:(python)