1.关于Python的非正式介绍

Python的非正式介绍

字符串

字符串外面所加的引号可能会改变,如果字符串中有单引号而没有双引号,该字符串外将加双引号来表示,否则就加单引号。print()会略去两边的引号,并且打印出经过转义的特数字字符:

和其他语言不一样的是, 特殊字符比如说 \n 在单引号 ('...') 和双引号 ("...") 里有一样的意义. 这两种引号唯一的区别是,你不需要在单引号里转义双引号 " (但是你必须把单引号转义成 \') , 反之亦然.

>>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"


>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'


>>> ' "Isn\'t," they said.'
'"Isn\'t," they said.'			# \'不影响引号的表示,所以\'没有被转义

>>> "'Isn\'t,'they said."		# \' 导致歧义。所有被转义
"'Isn't,'they said."

>>> '\'Isn\'t,\' they said.'
"'Isn't,' they said."			# 

>>> print('"Isn\'t," they said.')
"Isn't," they said.


>>> s = 'First line.\nSecond line.'
>>> s
'First line.\nSecond line.'
>>> print(s)
First line.
Second line.

如果不希望转义则前加r

>>> print('C:\some\name')
C:\some
ame
>>> print(r'C:\some\name')
C:\some\name

字符串可以被索引,正向或负向索引

>>> word = 'Python'
>>> word[0]
'P'
>>> word[5]
'n'
>>> word[-1]
'n'
>>> word[-3]
'h'

切片索引

>>> word[-2:]
'on'

索引过大会产生越界,但切片中的越界索引会被自动处理

>>> word[4:42]
'on'
>>> word[42:]

Python中的字符串不能被修改,它们是immutable的。因此,向字符串的某个索引位置赋值会产生一个错误

列表

列表的格式:

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

与字符串一样,列表也支持索引和切片,所有的切片操作都返回一个包含所请求元素的新列表,这意味着切片操作会返回列表的一个浅拷贝

>>> squares[:]
[1, 4, 9, 16, 25]

列表的内容可以改变。可以通过索引来改变元素,也可以在列表末尾通过append()方法来添加新元素;给切片赋值也是可以的,这样甚至可以改变列表大小,或者把列表整个清空:

>>> letters[:] = []
>>> letters
[]
posted @ 2022-06-28 16:48  Wang_Peicheng  阅读(28)  评论(0编辑  收藏  举报