1. 数值、字符串、列表类型在交互式中的使用——Python官网语法摘录

本文详细介绍了Python的基本数据类型和操作,包括数值运算、字符串处理、列表操作等,是Python初学者的入门指南。

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

1.数值
1.1 忽略小数部分
>>> 17 // 3
5
1.2 乘方

与es6语法相同

>>> 5 ** 2  # 5 squared
25
1.3 复数 的支持,使用后缀 j 或者 J 就可以表示虚数部分
>>>  a= 3+5j 
2.字符串
>>> word = 'Python'
2.1 原始字符串输出
>>> print(r'C:\some\name')  # note the r before the quote
C:\some\nam
2.2 字符串跨行连续输入。

字符串中的回车换行会自动包含到字符串中,如果不想包含,在行尾添加 \

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")
2.3 字符串用 + 进行连接,用 * 进行重复
2.4 两个或多个 字符串字自动连接到一起
>>> 'Py' 'thon'
'Python'
>>> text = ('Put several strings within parentheses '
...         'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
2.5 字符串索引

说明字符串也是数组

>>> word[0]  # character in position 0
'P'
>>> word[5]  # character in position 5
'n' 

2.6 字符串切片

>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1
2.7 字符串切片中的越界索引会被自动处理
>>> word[4:42]
'on'
>>> word[42:]
''
2.8 字符串不能被修改

字符串是 immutable 的,因此,向字符串的某个索引位置赋值会产生错误

>>>> word[0] = 'J'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
3.列表

列表是复合数据类型,一个列表可以包含多种数据类型

>>> squares = [1, 4, 9, 16, 25]
>>> cubes = [1, 8, 27, 65, 125] 
3.1 所有的切片操作都返回一个包含所请求元素的新列表
>>> squares[:]
[1, 4, 9, 16, 25]
3.2 列表拼接
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

列表是一个 mutable 类型,内容可以改变

3.3 append()
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]
3.4 通过切片赋值,改变列表大小,清空列表
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]
3.5 内置函数 len()

字符串也有

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)

————Blueicex 2020/07/19 11:12 blueice1980@126.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值