python语法学习

引用模块的两种形式

  • 形式1:import module-name import后面跟空格,然后是模块名称,例如:import os
  • 形式2: from module1 import module11 module1是一个大模块,里面还有子模块,只想用module11,就这么写了

list操作

`list.append(item)`   追加item元素到list列表
`list.insert(i,x)`    在i的位置添加x元素
如果i==len(list),意思是在最后一位追加,就等同于list.append(x)

`list.extend(list2)`  追加list2列表到list里面去
list2可以是字符串,也可以是list列表
>>> la = [1,2,3]
>>> b = "abc"
>>> la.extend(b)
>>> la
[1, 2, 3, 'a', 'b', 'c']

>>> la
[1, 2, 3, 'a', 'b', 'c']
>>> lb
['qiwsir', 'python']
>>> la[len(la):]=lb
>>> la
[1, 2, 3, 'a', 'b', 'c', 'qiwsir', 'python']

`list.count(x)`   list中x出现的次数
`list.index(x)`   x在list元素中所在的坐标



删除  
list.remove(x)   删除list的中的x元素
list.pop(i)    删除list中的下标为[i]的元素,如果没有写下标,默认删除最后一个

liststr之间的相互转换

line = "Hello.I am qiwsir.Welcome you."
line.split(".")     #以英文的句点为分隔符,得到list
['Hello', 'I am qiwsir', 'Welcome you', '']
如果 split()  中什么都不写,则表示用空格分割

name = ['Albert', 'Ainstain'];
 ".".join(name) 
得到 'Albert.Ainstain'


>>> squares = [x**2 for x in range(1,10)]
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81]


>>> aliquot = [n for n in range(1,100) if n%3==0]
>>> aliquot
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]


>>> print range(3,100,3)
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]

变量无类型,对象有类型

编码问题

  • 使用中文,首先在头部声明

coding:utf-8

  • 经验二:遇到字符(节)串,立刻转化为unicode,不要用str(),直接使用unicode()
unicode_str = unicode('中文', encoding='utf-8')
print unicode_str.encode('utf-8')
  • 经验三:如果对文件操作,打开文件的时候,最好用codecs.open,替代open(这个后面会讲到,先放在这里)
import codecs
codecs.open('filename', encoding='utf8')

你可能感兴趣的:(python语法学习)