Python2x——字符串

2017-11-16 14:44

Python目前的主要区别Python2与Python3,Python3有许多的优化,改版,有许多的语法使用方式与Python2有所区别。Python2x是指Python2.xx的版本,Python3则是指Python3.xx版本

什么是字符串?


字符串就是一个个字符串成一串,也就是单个的连在一起,经常看到的如下:

1
单引号的—— 'abc' , 'hello world'
2
3
双引号的——  "abc" , "hello world"

Python中的一般使用:

1
>>> print 'hello python'
2
hello python
3
>>> print "hello python"
4
hello python
5
>>>

也可以嵌套使用:

1
>>> print 'hello "python"'
2
hello "python"
3
>>> print "hello 'python'"
4
hello 'python'
5
>>>

注意输出的区别

1
错误的示范:
2
>>> print "hello 'py"t"hon'"
3
  File "<stdin>", line 1
4
    print "hello 'py"t"hon'"
5
                     ^
6
SyntaxError: invalid syntax
7
8
正确的示范:
9
>>> print "hello 'py't'hon'"
10
hello 'py't'hon'
11
12
13
错误的示范:
14
>>> print 'h"e'l'l"o'
15
  File "<stdin>", line 1
16
    print 'h"e'l'l"o'
17
               ^
18
SyntaxError: invalid syntax
19
20
错误的示范:
21
>>> print 'he"l'lo py'th"on'
22
  File "<stdin>", line 1
23
    print 'he"l'lo py'th"on'
24
                 ^
25
SyntaxError: invalid syntax
26
27
正确的示范:
28
>>> print 'he"l"lo py"th"on'
29
he"l"lo py"th"on
30
31
正确的示范:
32
>>> print 'he"l"l"o p"y"th"on'
33
he"l"l"o p"y"th"on

看看发现了什么,如果最外层用的是单引号'',单引号''里面嵌套的字符串需要再作引用说明时就只能是双引号""

同理亦然,最外层用了双引号"",字符串中间的就只能用单引号''

也就是说在Python2中一个字符串最外层的引用符号只能出现一次!

字符串的连接


1
1、
2
>>> print 'hello '+ " python"
3
hello  python
4
5
2、
6
>>> print "hello "+ " python"
7
hello  python
8
9
3、
10
>>> print 'hello '+' python'
11
hello  python

这几种都是可以的,通常为了提高代码的可读性,会统一用一种风格方式。约定好用第二种,或者第三种。不建议用第一种

其他类型转为字符串

最简单的一种就是用斜引号引用

1
>>> print "No"+`1`
2
No1

作为数字的1是不能和字符串相加的,因为两个类型不一样,同理类型不一样的时候是需要先统一类型再做处理的(整型/浮点型数据不在此类)。


标签: Python

License(CC)BY-NC-SA © 2017 — 2020 hadronw | Theme based on fzheng.me