栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 worldnhello kaolanhello pythonn'
>>> """
... hello world
... hello kaola
... hello python
... """
'nhello worldnhello kaolanhello pythonn'

字符串转义字符换行n

>>> print(''' hello wolrdn hello kaolan hello pythonn''')
 hello wolrd
 hello kaola
 hello python

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

打印出’hello n world’

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

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

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

合并字符串

  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'
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/998117.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号