python基础知识之字符串的表示、单/双/转义引号字符串、长字符串、原始字符串、unicode字符串
2016-12-01 10:03
337 查看
字符串的表示
通过python打印的字符串被引号括起来,而用print打印的值是希望用户看到的。>>>"hello" 'hello' >>>1000L 1000L >>> >>>print "hello" hello >>>print 1000L 1000 >>>
值被转化成字符串的三种机制:
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+\ +4 7 >>>
原始字符串
像路径“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' >>>
相关文章推荐
- Python基础语法——(引号、字符串、长字符串、原始字符串、Unicode)
- 第17课 Python中 字符串基础、转义字符串、原字符串、Unicode字符串、格式化字符串
- python 基础知识(字符串 序列)(2)
- python基础知识-字符串
- 【Python】Python的单引号字符串和转义引号
- Python语言编写用多行Unicode字符串表示下面的唐诗’静夜思‘并打印
- python基础知识-字符串的通用操作
- python的u'字符串"(字符编码):字符串前有u,表示字符串以unicode格式存储
- Python基础知识之认识字符串
- Python字符串-非转义和unicode
- python--基础学习(三)字符串单引号、双引号、三引号
- python 基础知识(字符串 序列)(2)
- Python 第一章 基础知识(9) 字符串
- python知识:json格式文本;异常处理;字符串处理;unicode类型和str类型转换
- Python基础知识(七)--字符串详解
- python基础知识(2)---使用字符串
- python基础知识-字符串的通用操作 分类: python 2012-11-29 19:57 252人阅读 评论(0) 收藏
- [Python学习] 专题三.字符串的基础知识
- Python学习笔记(一)--Python基础知识:变量、数据类型、模块与字符串
- python--基础学习(三)字符串单引号、双引号、三引号