Python字符串的运算及转义字符

字符串所用字符(’ ’ or " ")

>>> 'hello world'
'hello world'
>>> "hello world"
'hello world'

为什么既有单引号又有双引号

打印出let’s go

>>> "let's go"
"let's go"
>>> 'let\'s go'
"let's go"

终端打印多行

>>> '''
... hello world
... hello kaola
... hello python
... '''
'\nhello world\nhello kaola\nhello python\n'
>>> """
... hello world
... hello kaola
... hello python
... """
'\nhello world\nhello kaola\nhello python\n'

字符串转义字符换行\n

>>> print(''' hello wolrd\n hello kaola\n hello python\n''')
 hello wolrd
 hello kaola
 hello python

’ 单引号
\t 横向制表符(相当于tab)
\n 换行
\r 回车

打印出’hello \n world’

>>> print('hello \\n world')
hello \n world

使用场景一:打印出磁盘目录 c:\northwide\northwest
除了加转义符号外,还可以在字符串前加r或者R

>>> print('c:\northwide\northwest')
c:
orthwide
orthwest
>>> print('c:\\northwide\\northwest')
c:\northwide\northwest
>>> print(r'c:\northwide\northwest')
c:\northwide\northwest

合并字符串

  1. ‘+’ (拼接)
>>> 'hello'+'world'
'helloworld'
  1. ‘*’(重复)
>>> 'hello'*3
'hellohellohello'
  1. ‘[n]’(取对应索引下字符)
>>> 'hello world'[3]
'l'
>>> 'hello world'[0]
'h'
  1. ‘[-n]’(从后往前数)
>>> 'hello world'[-5]
'w'
  1. ‘[m:n]’(截取一串字符)
>>> 'hello world'[0:4]
'hell'
>>> 'hello world'[0:-1]
'hello worl'
  1. ‘[m:]’(从索引m截取到字符串的末尾)
>>> 'hello world'[6:]
'world'

7.‘[-m:]’ 如果字符串很长的情况下从末尾开始截取

>>> 'hello java python c# ruby'[-4:]
'ruby'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值