Python学习笔记(一)

来源:互联网 发布:地下城组队网络冲突 编辑:程序博客网 时间:2024/06/06 03:19

   《Python学习手册》学习笔记
   我的Python版本是2.7,由于其它环境不兼容3.x。
   “>>>”后面的是用户输入的命令,机器返回值前面则没有标志。

   数字
   分为整数、浮点数、以及更为少见的类型(有虚部的复数、固定精度的十进制数等)
   

>>> 123+111234>>> 1.5*46.0>>> 2**4  #次方运算符,Python中#是注释符号16>>> len(str(2**100)) #计算数字的长度,需要先转换为string类型31

   也可以使用数学模块,模块只不过是我们导入以供使用的一些额外工具包。
   

>>> import math>>> math.pi3.141592653589793>>> math.sqrt(81) #开方运算符9.0>>> math.pow(2,4) #乘方运算符16.0

   还有随机数模块,用以生成随机数和相关方法:
   

>>> import random>>> random.random() #0到1之间的浮点数0.8460230849617111>>> random.choice([1,2,3]) #在几个选项中随机选取某个值3>>> random.randint (3,6) #生成3到6之间的整数5

   字符串
   

>>> a = 'Ellen'>>> len(a)  #输入字符串的长度5>>> a[4] #输出某个位置的字符,字符顺序从‘0’开始'n'>>> a[-2] #可以使用反向索引,最后一个字符索引是‘-1’,以此类推'e'>>> a[-1-2] #可以在中括号内进行数值运算'l'
>>> a[1:4]  #可以进行“分片”操作,从‘1’到‘4’,但不包括‘4’位置的字符'lle'>>> a[1:] #冒号后面默认为字符串尾'llen'>>> a[:3]  #冒号前面默认字符串首'Ell'>>> a[:-1]'Elle'>>> >>> a[:]'Ellen'

   字符串可以进行合并操作:

>>> a + 'haha''Ellenhaha'>>> a * 3'EllenEllenEllen'

   不可变性:以上的例子中我们并没有通过任何操作最原始的字符串进行改变。字符串在Python中具有不可变性——在创建后不能就地改变。例如,不能通过对其某一位置进行赋值而改变字符串。
   例如,如果我们要改变某一字符,下面的命令会报错:

>>> a[2] ='b'Traceback (most recent call last):  File "<pyshell#53>", line 1, in <module>    a[2] ='b'TypeError: 'str' object does not support item assignment

   字符串还有一些独有的操作方法,比如find()和replace()方法:
   

>>> a.find('e')3>>> a.replace('en','abc')'Ellabc'>>> a #注意a字符串依然没有任何变化'Ellen'

   
   还有很多实用的方法:
   

>>> b='www.baidu.com'>>> b.split('.') #按照某个字符分隔字符串['www', 'baidu', 'com']>>> a.upper() #全部转为大写字母'ELLEN'>>> a.isalpha () #判断值是否是字符True>>> c='111'>>> c.isalpha ()False>>> c.isdigit() #判断值是否是数字True>>> d=' sdfsd  '>>>> d.rstrip() #去除字符串右面的空白字符' sdfsd'

   字符串还支持一个叫格式化的高级替代操作,可以易表达式的形式和一个字符串方法调用形式使用,类似C语言格式化输出:printf("result is %d", num);

>>> '%s, my name is %s.'%('hello', 'Ellen') #第一种方式'hello, my name is Ellen.'>>> "{0}, what's your {1}".format('ok', 'name')  #第二种方式"ok, what's your name"

   我们也可以查看某个类型的属性:
   

>>> a'Ellen'>>> dir(a)  #使用dir()方法['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

   dir()方法列出了方法的名称,如果我们要知道它们是做什么的,可以使用help()函数:
   

>>> help(a.upper)Help on built-in function upper:upper(...)    S.upper() -> string    Return a copy of the string S converted to uppercase.

   其它编写字符串的方法:
   

>>> a='a\nb\tc'>>> a'a\nb\tc'>>> len(a)5>>> ord('a')  #返回字符的ASCII码97

   还可以使用三引号来更方便的输出字符串:
   

>>> msg = 'hello\nworld\nim python'>>> msg'hello\nworld\nim python'>>> print(msg)helloworldim python

      使用三引号就变为了:
      

>>> msg = """helloworldim python""">>> msg'hello\nworld\nim python'>>> print(msg)helloworldim python

   这是一个微妙的语法上的便捷方式,但是在做拼接HTML代码段这样的工作时则会方便不少!

0 0
原创粉丝点击