Python3.6.5 笔记:字符串中的转义字符\,\n,取消转义r,长字符串,字符串的索引

字符串可以 ('...')  ("...") 引用。  


 \ 是转义字符

例如在终端输入:

例子1:

>>> 'doesn\'t'
"doesn't"

或者

>>> "doesn't"
"doesn't"

例子2:

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

或者

>>> '"Yes,"he said.'
'"Yes,"he said.'

例子3:(note:当在终端里输入如下命令时)

>>> '"Isn\'t."she said.'
'"Isn\'t."she said.'
>>> print('"Isn\'t."she said.')
"Isn't."she said.


\n 是用来换行的

例子4:

>>> 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


输出长字符串"""..."""或者'''...'''
>>> print("""\
... ... usage:thingy [options]
... ...      -h  display this usage message
... ...      -H hostname hostname to connect to
... ... """)
... usage:thingy [options]
...      -h  display this usage message
...      -H hostname hostname to connect to


字符串中的*与+
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'


两个相邻的字符串会自动拼接到一起(只应用于字面量,如果拼接字符串变量与字面量,可以使用+)
>>> '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.'


字符串可以被indexed,可以使用切片
>>> word = 'Python'
>>> word[:2] + word[2:]
'Python'
下图可以用来记忆字符串index,left number作为相应字符的索引
 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

字符串item不能改变
>>> word[0] = 'J'
  ...
TypeError: 'str' object does not support item assignment
built-in function len(str)返回字符串str的长度


  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值