数字,字符串,列表

Numbers

>>> 18/4    #/除返回的总是浮点数
4.5
>>> 5/5
1.0
>>> 18//4     #地板除,返回的是整数
4
>>> _*4       #下划线代表最近一个表达式的值
16

除了int和float,python还支持其他的数字类型,如: Decimal和 Fraction。还有内置的复数类型complex:3+2j/3+2

Strings

>>> 'hello'   #单引号
'hello'
>>> "I'm a girl"   #双引号
"I'm a girl"
>>> 'I\'m not a boy'   #反斜杠转义
"I'm not a boy"
>>> print("hello\n world")  #\n换行
hello
 world
>>> print(r"hello\n world")    #r原始字符串,\n不换行
hello\n world
>>> "hello "*3+"world"  # *字符串重复,+字符串连接
'hello hello hello world'
>>> word='python'
>>> word[0]
'p'
>>> word[5]
'n'
>>> word[-1]
'n'
>>> word[-2]
'o'
>>> len(word)   #长度
6
>>> word[:2]    #切片操作
'py'
>>> word[2:]
'thon'
>>> word[2:4]
'th'
>>> word[-2]
'o'
>>> word[-2:]
'on'
>>> word[42]    #下标超过范围报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> word[4:42]    #切片超过范围不报错
'on'
>>> word[0]='J'   #字符串不能修改
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

Lists

>>> cubes=[1,8,27,66]    #列表
>>> cubes[0]
1
>>> cubes[-1]
66
>>> cubes[:]
[1, 8, 27, 66]
>>> cubes[-3:]
[8, 27, 66]
>>> cubes.append(343)   #后面添加元素
>>> cubes
[1, 8, 27, 66, 343]
>>> cubes=cubes+[125,216]   #连接
>>> cubes
[1, 8, 27, 66, 343, 125, 216]
>>> cubes*2   #重复
[1, 8, 27, 66, 343, 125, 216, 1, 8, 27, 66, 343, 125, 216]
>>>s=[1,2,3,4,5,6,7]
>>> s[2:5]=['C','D','E']   #修改
>>> s
[1, 2, 'C', 'D', 'E', 6, 7]
>>> s[2:5]=[]   #修改
>>> s
[1, 2, 6, 7]
>>> s[:]=[]   #修改
>>> s
[]
b
>>> s=[1,2,3,4,5,6,7]
>>> len(s)   #长度
7
>>> a=[1,2]
>>> b=['c','d']
>>> s=[a,b]   #二维数组
>>> s
[[1, 2], ['c', 'd']]
>>> s[1][0]
'c'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值