Python学习笔记(一)

本文介绍了Python的基础知识,包括数字运算、字符串操作以及常用模块的使用,如数学模块和随机数模块。文章通过实例演示了加减乘除、指数运算、字符串长度获取及分片等操作,并解释了字符串的不可变性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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

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

>>> import math
>>> math.pi
3.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)
hello
world
im python

      使用三引号就变为了:
      

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值