python

导航

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

来源 :中华考试网 2020-10-23

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

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

1

2

3

4

5

<p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">>>> 'my python lession'       #以单引号将字符串扩起来

'my python lession'

>>> a = 'my python lession'  

>>> print(a)

my python lession<br></span></p>

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

1

2

3

4

5

<p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">>>> "my python lession"    #使用双引号将字符串扩起来

'my python lession'

>>> a = "my python lession"

>>> print(a)

my python lession<br></span></p>

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">>>> '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<br></span></p>

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

<p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">>>> '"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<br></span></p>

分享到

相关资讯