字符串在Python中如何表达出来

对于字符串,最通俗易懂理解的字面意思是一串字符。那么,在Python中如何表达字符串呢?接下来本文为大家详细讲解:

1.使用单引号扩起来字符串

>>> 'my python lession'       #以单引号将字符串扩起来 'my python lession' >>> a = 'my python lession'   >>> print(a) my python lession

2.使用双引号将字符串扩起来

>>> "my python lession"    #使用双引号将字符串扩起来 'my python lession' >>> a = "my python lession" >>> print(a) my python lession

值得说明的是,被单引号(single quote)或双引号(double quotes)包围的字符串,这两者的作用是一样的:

3.当想要输出单引号或者双引号时(将单引号,双引号作为普通字符输出),通过 进行转义

>>> 'python 'escape'           "python 'escape" >>> a = 'python 'escape' >>> print(a) python 'escape     #通过反斜线将单引号进行转移,不在乎最外层的是单引号还是双引号,反正是中间是字符串,有就将后面的单引号,双引号进行转义 >>> >>> 'python " escape' 'python " escape' >>> a = 'python " escape' >>> print(a) python " escape >>> >>> "python ' escape" "python ' escape" >>> a = "python ' escape" >>> print(a) python ' escape >>> >>> "python " escape" 'python " escape' >>> a = "python " escape" >>> print(a) python " escape

4.通过单引号,双引号混合的方式输出单引号,双引号

>>> '"double quote"'    #单引号中,使用双引号,直接将双引号输出 '"double quote"' >>> a = '"double quote"' >>> print(a) "double quote" >>> >>> "'single quote'"     #双引号中,使用单引号,将单引号输出 "'single quote'" >>> a = "'single quote'" >>> print(a) 'single quote' >>> >>> ""double""   #双引号中直接输出双引号报错 SyntaxError: invalid syntax >>> ""double""  #双引号中直接输出双引号报错,但是将其中的双引号通过反斜线进行转义就可以了 '"double"' >>> a = ""double"" >>> print(a) "double" >>> >>> ''single''  #单引号中输出单引号字符报错,加上转义字符就可以了。 SyntaxError: invalid syntax >>> ''single'' "'single'" >>> a = ''single'' >>> print(a) 'single' >>> '"My python', lession'  #单引号中输出双引号可以,如有单引号,必须进行转义 SyntaxError: EOL while scanning string literal >>> '"My python', lession' '"My python', lession' >>> a = '"My python', lession' >>> print(a) "My python', lession

学会了字符串在Python中的表达方式,在下篇中我们继续学习,让字符串在Python中拼接起来。

来源:PY学习网:原文地址:https://www.py.cn/article.html

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » 字符串在Python中如何表达出来