sxyzy 发表于 2018-8-13 13:18:33

Python3.5修炼手册5-duyuheng

  字符串操作
  字符串是python中最常用的数据类型。我们可以使用''或""创建字符串。
  通常字符不能进行数学操作,即使看起来像数字也不行。字符串不能进行除法、减法和字符串之间的乘法运算
  字符串可以使用操作符+,但功能和数学的不一样,它会进行拼接(concatenation)操作,将后面两个字符首尾连接起来
  例如:
>>> string1='hello'  
>>> string2='world'
  
>>> print(string1+string2)
  helloworld
  如想让字符直接有空格,可以建一个空字符变量插在字符串之间,让字符串隔开,或者在字符串中加入相应的空格
>>> string1='hello'  
>>> string2='world'
  
>>> space=' '
  
>>> print(string1+space+string2)
  hello world
  也可以这样
>>> string1='hello'  
>>> string2=' world'
  
>>> print(string1+space+string2)
  helloworld
  注释
  注释(comments)必须以#号开始,可以独占一行也可以放的语句的末尾
  例如:
>>> #打印1+1的结果  
... print(1+1)
  2
>>> print(2+2) #打印2+2的结果  4
  从#开始后面的内容都会被忽略掉
  调试
  如果用int()转换一个字符会怎么样?
>>> int('hello')  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ValueError: invalid literal for int() with base 10: 'hello'
  报错:ValueError:用于int()的无效文字,使用基数为10:“hello”
  在变量和关键字中,如果变量被命名为关键字结果会怎么样?
>>> class="hello"  File "<stdin>", line 1
  ^
  SyntaxError: invalid syntax
  报错:SyntaxError:无效的语法
  在算数运算中,如果被除数为0,结果会怎么样?
>>> 9/0  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ZeroDivisionError: division by zero
  报错:ZeroDivisionError:除零
  这里的被除数和数学里面的一样,不能为0.
页: [1]
查看完整版本: Python3.5修炼手册5-duyuheng