1.1.2 Python字符串连接,转义字符
2018-03-02 09:20
218 查看
一,字符串把两个数字用“+”符号连接起来,比如3+5,结果为8,字符串用“+”连接:>>> 'he'+'llo''hello'用“+”号实现连接的确比较简单,不过,有时候你会遇到这样的问题:>>> a=1988>>> b="hello">>> a+b
Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> a+bTypeError: unsupported operand type(s) for +: 'int' and 'str'修改上面的错误,可以通过以下方法:>>> print b+`a`hello1988注意:``是反引号,不是单引号,就是键盘中通常在数字1左边的那个键,在英文半角状态下输入的符号。这种方法,在编程实践中较少应用,特别是在Python 3中,已经把这种方式弃绝了。我想原因就是这个符号太容易和单引号混淆了,且在编程中也不容易看出来,可读性太差。反引号竟然不让用,肯定需要解决方法:>>> print b+str(a)hello1988用str(a)实现将整数对象转换为字符串对象。虽然str是一种对象类型,但是它也能够实现对象类型的转换,这就起到了一个函数的作用。int也有类似的作用:>>> a="2015">>> type(a)<type 'str'>>>> b=int(a)>>> type(b)<type 'int'>如果你对int和str比较好奇,可以在交互模式中使用help(int),学习help(str)还有第三种:>>> a=1988>>> b="hello">>> print b+repr(a)hello1988这里repr()是一个函数,其实就是反引号的替代品,它能够把结果字符串转化为合法的Python表达式。二,转义字符转义字符 描述\ (在行尾时)续行符,(不在行尾时)转义符\' 单引号\" 双引号\b 退格(Backspace)\n 换行\r 回车测试:>>> "hello1988"\
4000
"gogoh"'hello1988gogoh'>>> "hello1988"\"wolaile"'hello1988wolaile'>>> print "hello \nword"hello word在测试中遇到一些问题:>>> "hello \n word"'hello \n word'>>> print "hello \nword"hello word解决:>>> print r"hello \n word"hello \n word由r开头引起的字符串就是声明了后面引号里的东西是原始字符串,在里面放任何字符都表示该字符的原始含义。
Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> a+bTypeError: unsupported operand type(s) for +: 'int' and 'str'修改上面的错误,可以通过以下方法:>>> print b+`a`hello1988注意:``是反引号,不是单引号,就是键盘中通常在数字1左边的那个键,在英文半角状态下输入的符号。这种方法,在编程实践中较少应用,特别是在Python 3中,已经把这种方式弃绝了。我想原因就是这个符号太容易和单引号混淆了,且在编程中也不容易看出来,可读性太差。反引号竟然不让用,肯定需要解决方法:>>> print b+str(a)hello1988用str(a)实现将整数对象转换为字符串对象。虽然str是一种对象类型,但是它也能够实现对象类型的转换,这就起到了一个函数的作用。int也有类似的作用:>>> a="2015">>> type(a)<type 'str'>>>> b=int(a)>>> type(b)<type 'int'>如果你对int和str比较好奇,可以在交互模式中使用help(int),学习help(str)还有第三种:>>> a=1988>>> b="hello">>> print b+repr(a)hello1988这里repr()是一个函数,其实就是反引号的替代品,它能够把结果字符串转化为合法的Python表达式。二,转义字符转义字符 描述\ (在行尾时)续行符,(不在行尾时)转义符\' 单引号\" 双引号\b 退格(Backspace)\n 换行\r 回车测试:>>> "hello1988"\
4000
"gogoh"'hello1988gogoh'>>> "hello1988"\"wolaile"'hello1988wolaile'>>> print "hello \nword"hello word在测试中遇到一些问题:>>> "hello \n word"'hello \n word'>>> print "hello \nword"hello word解决:>>> print r"hello \n word"hello \n word由r开头引起的字符串就是声明了后面引号里的东西是原始字符串,在里面放任何字符都表示该字符的原始含义。
相关文章推荐
- python_11(format、转义字符、连接字符、字符串操作函数、字符串反转)
- python中字符串连接的四种方式
- python join连接字符串Demo
- 黄聪:Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- python的字符串连接
- python string字符串的8种连接方式
- python list 合并连接字符串的方法
- python连接字符串的方式、效率及适用场景
- Python学习笔记-- 字符串和数字的连接
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- python字符串连接导致效率问题
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- python字符串连接方法
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python格式化字符串和转义字符
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- 黄聪:Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- python字符串连接的N种方式
- python string字符串的8种连接方式