python基础知识之字符串的表示、单/双/转义引号字符串、长字符串、原始字符串、unicode字符串

来源:互联网 发布:立花瑠莉 知乎 编辑:程序博客网 时间:2024/06/05 14:27

字符串的表示

通过python打印的字符串被引号括起来,而用print打印的值是希望用户看到的。

>>>"hello"'hello'>>>1000L1000L>>>>>>print "hello"hello>>>print 1000L1000>>>

值被转化成字符串的三种机制:
str函数
把值转化为合理形式的字符串,以便用户可以理解。

>>> print str("hello")hello>>>print str(1000L)1000>>>

repr函数
创建一个字符串,以合法的python表达式的形式来表示值。

>>> print repr("hello")'hello'>>> print repr(1000L)1000L>>>

反引号 “
打印一个包含数的句子。

>>> temp=42>>> print "the number is:"+`temp`the number is:42>>> print "the number is:"+str(temp)the number is:42>>> print "the number is:"+repr(temp)the number is:42>>>

单/双引号字符串

>>>"hello,world!"'hello,world!'>>>'hello,world!''hello,world!'>>>

打印字符串时,使用单或双引号括起来,没有区别。但是在某些情况下,两者同时存在:

>>>'let's go!'SyntaxError: invalid syntax>>>"let's go!""let's go!">>>'"hello!",he said''"hello!",he said'>>>

转义字符串

使用反斜杠“\”对字符串中的引号进行转义。

>>>'let\'s go!'"let\'s go!">>>"\"hello\",he said"'"hello",he said'>>>

长字符串(即三引号字符串)

前面两种书写字符串方法在字符串很长时不适用,而使用三引号(三个双引号或三个单引号)时,字符串可跨行,可同时使用单引号和双引号,不需要进行转义。

>>>'''this is a long story,there was agirl.''''this is a long story,\nthere was agirl.'>>>"""this is a long story,there was agirl."""'this is a long story,\nthere was agirl.'>>>

讲到长字符串,有必要提一下字符串的拼接问题。
拼接字符串

方法1:
一个接一个的方式

>>> "let's say"'"hello"''let\'s say"hello"'>>>

方法2:
使用“+”

>>> x='hello,'>>> y='world'>>> print (x+y)hello,world>>>

普通字符串跨行:一行中最后的一个字符是反斜杠。

>>> print"hello,\world"hello,world>>>print \          "hello,world"hello, world>>> 1+2+\         +47>>>

原始字符串

像路径“c:\nowhere”这种字符串,不希望反斜杠有特殊转义作用,有两种方法:
方法1:使用反斜杠对反斜杠进行转义。

>>> print "c:\\nowhere"c:\nowhere>>>

方法2:字符串以“r”开头

>>>print  r"c:\nowhere"c:\nowhere>>>

原始字符串的结尾不能是反斜杠,除非对反斜杠进行转义。

>>>print "c:\\nowhere\"SyntaxError: EOL while scanning string literal>>>print "c:\\nowhere\\"c:\nowhere\>>>

Unicode字符串

unicode字符串使用前用“u”前缀,存储单位为16位的unicode字符。

>>> u'hello'u'hello'>>>>>> u'中'u'\xd6\xd0'>>> u'中国'u'\xd6\xd0\xb9\xfa'>>>
0 0
原创粉丝点击