Python 学习笔记1

1、 在使用了“from模块import函数”这种形式的命令之后可以直接使用函数,而不需要模块名作为前缀,

例如:

>>>from math import sqrt

>>>sqrt(9)

3.0

有些时候只用普通的import,以免引起一些冲突之类的

例如:

>>> import cmath

>>>cmath.sqrt(-1)

1j

2、转义引号

使用反斜杠(\)对字符串中的引号进行转义:
>>> 'Let\'s go!
Let's go!

使用反斜杠(\)对字符串中的\ 进行转义:
>>> print "c:\\Software"
c:\Software
>>>

3、字符串表示,str 和 repr 或者反引号(注:python3.0版本不再使用反引号)


>>> print "Hello"+str(1000 L)
Hello1000
>>> print "Hello"+`1000 L`
Hello1000 L
>>> print "Hello"+repr(1000 L)
Hello1000 L

>>>


4、Unicode字符

Python2.x版本编写的程序默认采用ASCII编码,这个通过sys模块便能直接看到看到。(python3.0 字符都是Unicode编码)

       Import sys

       Print sys.getdefaultencodeing()

ASCII是8位编码,Unicode是16位编码

中文字串应该加上u'测试成功!'


5、列表&元组

列表是可变的,元组和字符串是不可变的
1)列表:
list 函数
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
>>>
赋值
>>> x=[0,1,0]
>>> x[1]=3
>>> x
[0, 3, 0]
>>>
分片赋值
>>> list1=list('hello')
>>> list1
['h', 'e', 'l', 'l', 'o']
>>> list1[1:]=[1,2,3,4]
>>> list1
['h', 1, 2, 3, 4]
>>>

追加元素
>>> list1.append(5)
>>> list1
['h', 1, 2, 3, 4, 5]
>>>
删除
>>> del x[1]
>>> x
[0, 0]
>>>

方法(函数)汇总:
序号 方法
1 list.append(obj)
在列表末尾添加新的对象
2 list.count(obj)
统计某个元素在列表中出现的次数
3 list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4 list.index(obj)
从列表中找出某个值第一个匹配项的索引位置
5 list.insert(index, obj)
将对象插入列表
6 list.pop(obj=list[-1])
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
7 list.remove(obj)
移除列表中某个值的第一个匹配项
8 list.reverse()
反向列表中元素
9 list.sort([func])
对原列表进行排序

2)元组:

>>> tuple('tuple')
('t', 'u', 'p', 'l', 'e')
>>>
元组输出时用的(),list输出时是[ ]

猜你喜欢

转载自blog.csdn.net/tx_programming/article/details/73995869