Python学习笔记2-Python神奇的语法和格式化输出
2015-12-29 22:36
956 查看
先来看一个例子:
Python是非常简化的语言,所以类与方法之间没有大括号,连if判断的代码块都没有大括号;类的实例不需要使用new关键字;
代码的结尾分号也被省略掉了,这让写习惯Java代码的我,刚上手很不习惯;
但Python对格式要求很严格,不同层次的代码必须要对齐,要不然会报错;
Python 语法:
行注释使用“#” 进行注释,例:
块注释使用三个单撇号 ''' ,例:
可以使用\来使代码进行换行 例:
不等于号可以使用<>或者!= 都可以,例:
在Python中字符串可以使用单引号或者双引号
与、或、非逻辑符号分别使用 and、or、not None
Python 变量赋值
更多Python 数值/字符串格式化
http://blog.csdn.net/feelang/article/details/37594313
http://www.cnblogs.com/plwang1990/p/3757549.html
字符串操作
class Fish: hungry=True def eat(self,food): if food is not None: self.hungry=False class User: def __init__(self,name): self.name=name f=Fish() Fish.eat(f, None) print(f.hungry) Fish.eat(f,'rice') f.eat('noodle') print(f.hungry) user=User('zhangsan') print(user.name)
Python是非常简化的语言,所以类与方法之间没有大括号,连if判断的代码块都没有大括号;类的实例不需要使用new关键字;
代码的结尾分号也被省略掉了,这让写习惯Java代码的我,刚上手很不习惯;
但Python对格式要求很严格,不同层次的代码必须要对齐,要不然会报错;
Python 语法:
行注释使用“#” 进行注释,例:
# 这是一个注释
块注释使用三个单撇号 ''' ,例:
''' 这是一个块注释 '''
可以使用\来使代码进行换行 例:
str1=None str2=None if(str1<>1) and \ (str2<>1): print "两个变量都不等于1"
不等于号可以使用<>或者!= 都可以,例:
print 1<>2 print 1!=2
在Python中字符串可以使用单引号或者双引号
print '这是一个字符串' print "这是一个字符串"
与、或、非逻辑符号分别使用 and、or、not None
print True and False # False print True or False # True print not not None # False
Python 变量赋值
count=0 count=count+1 #这里count++或者++count无效的 count+=1 count*=1 count-=1 print count name='bobi' print name x=y=z=1 #可以三个变量一起赋值 print x,y,z x,y,z=1,'string',0.5 #可以实现不同类型变量一起赋值 print x,y,z x,y=y,x #可以这样实现变量之间的值的调换 print x,y x,y=15.5,24.2 print 'x: %d,y: %d' % (x,y) #格式化为整数 print 'x: %f,y: %f' % (x,y) #格式化为浮点数 print 'x: %x,y: %x' % (x,y) #格式化为十六进制数 print 'x: %o,y: %o' % (x,y) #格式化为八进制数 print '两位小数:%.2f' % (1.765555) #保留两位小数 print 'My name is %s,i\'m %s.' % ('Tom',18) #带入字符串
更多Python 数值/字符串格式化
http://blog.csdn.net/feelang/article/details/37594313
http://www.cnblogs.com/plwang1990/p/3757549.html
字符串操作
str='Python' print str[0] # 取第一位 P print str[2:5] # 取2~5之间的 tho print str[:2] # 取前两位 Py print str[3:] # 取第三位开始到最后hon print str[-1] # 取最后一位 n print str[:] # 取所有 print str cool=' is Cool' print str+cool # 字符串与字符串相加 print str+' '+cool # 字符串与字符串相加 print str*2 # 相当于 str + str 两个字符串相加 str=1000 # 变量可以进行任意数据类型转换 print str print '#'*20 # '#'乘以20个#
相关文章推荐
- Python学习笔记2-Python神奇的语法和格式化输出
- python笔记01--list,map使用
- 【转】Python IDE for Eclipse
- python flask 学习笔记1 简单入门
- Python实现二路归并排序
- python学习之列表和字典
- python中的str,unicode和gb2312
- python函数与方法装饰器
- 使用Python和Splinter实现12306火车票查询与抢票
- python国际化
- ZBar大图像处理加速
- numpy 常用api(三)
- leetcode之Path Sum II
- python中if __name__ == '__main__': 的解析
- Python爬虫学习笔记——豆瓣登陆(一)
- python中关于处理汉字乱码的问题
- python 3.5 爬虫日记1
- 编写高质量代码--改善python程序的建议(一)
- python --subprocess 范例
- 二、纯 python 实现一个调试器