Python_学习_字符串和数字
来源:互联网 发布:数据库报表是什么 编辑:程序博客网 时间:2024/06/10 04:07
作为Python的小白,许多知识需要一点点的积累:
1,在Python语句里,if 语句后需要加上冒号,否则会报错:
>>> myval=None
>>> print(myval)
None
>>> if myval == None
SyntaxError: invalid syntax
>>> print(myval)
None
>>> if myval==None:
print("The variable myval doesn't have a value")
The variable myval doesn't have a value
2,在Python中‘10’和10的意义不同,前者作为字符串,而后者作为数字。前者不可以直接比较大小,后者是可以的。
需要转换的话,可以使用int函数和str函数进行转化。
>>> age='10'>>> converted_age=int(age)
>>> if converted_age==10:
print("Hello")
Hello
>>> age=10
>>> converted_age=str(age)
>>> if converted_age==10:
print("Fail")
需要注意的是,如果想要转换带小数点的数字,会得到一条错误的提示:
>>> age='10.5'
>>> converted_age=int(age)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
converted_age=int(age)
ValueError: invalid literal for int() with base 10: '10.5'
改正的方法是,用float来代替int 。 float函数可以处理不是整数类型的数字。
>>> age='10.5'
>>> converted_age=float(age)
>>> print(converted_age)
10.5
如果要把没有数字的字符串改成数字,也会得到错误的提示:
>>> age='ten'
>>> converted_age=int(age)
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
converted_age=int(age)
ValueError: invalid literal for int() with base 10: 'ten'
- Python_学习_字符串和数字
- 04-python_数据类型-数字和字符串
- [学习笔记]Python_字符串
- OC_学习_数字对象和字符串NSString
- python_>>_<<
- python_学习笔记_基础练习_1
- python_学习笔记_基础练习_2
- 01_自动化Python_学习概述
- [学习笔记]Python_字符串,元祖,字典
- Python_字符串
- 【QT学习】字符串和数字
- 【QT学习】字符串和数字
- Ruby学习-数字和字符串
- python_基础学习_命名规范/编码/注解
- javascript学习 - 数字和字符串转换
- Python学习笔记五:数字和字符串
- python_格式化字符串
- Python_格式化字符串
- oracle 12c:新特性-如何在RMAN中执行SQL语句
- 对Java中关键字的认知
- SPI子系统驱动架构 - 具体实现
- JAVA之多线程的安全问题(线程同步)
- springmvc 整合 shiro
- Python_学习_字符串和数字
- javaScript--04 JavaScript基础&DOM 上
- C语言复合数据类型
- mybatis+oracle主键自增
- Pear Trees
- 多线程笔记
- 给groupBox添加滚动条
- Java提高篇(三四)-----fail-fast机制
- Window的对象Scroll