python 学习笔记 字符串(2)

一、字符串的三种表示法

  1、使用单引号(')

    例如:

print 'hello world'

  2、使用双引号(")

    例如:

print "hello world"

  3、使用三引号('''或"""), 三引号可以包含多行字串, 并签中间可以任意使用单引号或双引号。

    例如:

print '''hello world, "this's is
hello word."
可以是多行
'''

print """hello world, "this's is
hello word."
可以是多行
"""

二、转义字符的使用

  如果想在单引号里使用单引号, 或是双引号里使用双引号,那么可以通过转义字符来实现, \'代表单引号, \"代表双引号,\\代表反斜杠, 在行末使用\代表续行, 即下一行与\所在的行为同一个字符串.

  例如:

print 'this\'s hello world'
输出结果是
this's hello world

以上代码也可以表示为

print "this's hello world"

使用\换行的例子

print "hello world, \
this's same line with hello world
"
输出结果为:
hello world, this's same line with hello world

三、自然字符串

  使用r或R标识后边的字符串中不使用转义字符, 常用于正则表达式.

例如:

print r"\n想输出反斜杠后边跟一个n"
输出结果为:
\n

四、Unicode字符串

  使用u或U标识后边的字符串使用Unicode编码

五、字符串连接

  将两个字符串放到一起, 将自动连接, 字符串之间可以有空格.

  例如:

print 'hello''world'
输出结果是: helloworld

六、注意事项和建议

1 单引号和双引号没有任何区别
2 当使用正则表达式时, 建议使用自然字串, 即用r或R后边跟一个字符串
3 当有单引号和双引号混用的情况时, 建议使用三引号



 

原文地址:https://www.cnblogs.com/liubin0509/p/2263848.html