您的位置:首页 > 编程语言 > Python开发

Python学习笔记2-Python神奇的语法和格式化输出

2015-12-29 22:36 956 查看
先来看一个例子:

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个#
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: