当前位置: 移动技术网 > IT编程>脚本编程>Python > Python 学习笔记(七)Python字符串(一)

Python 学习笔记(七)Python字符串(一)

2018年03月12日  | 移动技术网IT编程  | 我要评论

无忧花开中文版普通话,绿岛救援,平鲁吧

字符串

字符串或串(String)是由数字、字母、下划线组成的一串字符,用双引号或单引号包裹的为字符串

1 >>> "hello world"
2 'hello world'
3 >>> 'hello world'
4 'hello world'
5 >>> "250"
6 '250'
7 >>> type("200")
8 <type 'str'>

   下面示例:

  语法错误 第一行出现三个单引号,Python 解析器匹配不上成对的引号,所以报错。

  解决方法:1、可使用双引号包裹 2、可以使用反斜杠\ 转义字符

 1 >>> 'What's your name?'
 2   File "<stdin>", line 1
 3     'What's your name?'
 4           ^
 5 SyntaxError: invalid syntax
 6 >>> "What's your name?"
 7 "What's your name?"
 8 >>> 'What\'s your name?'
 9 "What's your name?"
10 >>>

  字符串 、数字互转

  内置函数int()  str() float()

 1 >>> a = int("200")
 2 >>> a
 3 200
 4 >>> type(a)
 5 <type 'int'>
 6 >>> b = str(200)
 7 >>> type(b)
 8 <type 'str'>
 9 >>> c = float("200.5")
10 >>> type(c)
11 <type 'float'>
12 >>>

  转义符

 第5行出现 \n 换行

 解决方法:使用反斜杠\ 或者在原始字符串前+r ,会显示原始字符串

1 >>> print "c:\\news"
2 c:\news
3 >>> print r"c:\news"
4 c:\news
5 >>> print "c:\news"
6 c:
7 ews

字符串相加

 字符串相加是将两个字符串拼接在一起

 1 >>> "3" + "6"
 2 '36'
 3 >>> "py" + "thon"
 4 'python'
 5 >>> 8 + "6"
 6 Traceback (most recent call last):
 7   File "<stdin>", line 1, in <module>
 8 TypeError: unsupported operand type(s) for +: 'int' and 'str'  不支持 int 和字符串相加,我们可以将其转换
 9 >>> 8 + int("6")
10 14
11 >>> str("8")+ "6"
12 '86'

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网