python语法
来源:原创
时间:2018-08-26
作者:脚本小站
分类:其他
整除:
>>> 12 // 5 2
求余:
>>> 2121 % 11 9
幂运算
>>> 2**3 8 >>> pow(2, 3) 8
拼接字符串用 “+”:
>>> a = "hello " >>> b = "world" >>> a + b 'hello world'
is 判断变量值是否相同:
var1 = "hello" var2 = "hello" var1 is var2 True
输入函数:
var = input("input something:") #python3 print var var = raw_input("input something:") #python2 print var
格式化输出:
>>> num = 123.456 >>> print "The num is %f" % num The num is 123.456000 >>> num2 = 4343 >>> print "The nums are %f and %d" % (num, num2) The nums are 123.456000 and 4343
查看内建函数:
dir(__builtins__)
查看某个函数的使用方法:
help(str)
示例:
>>> name = "tom" >>> name.upper()
ptint:
>>> print "%-20.15f" % (-3.1)
json格式:
>>> d = {'a':32, 'b':32} >>> d['a'] 32
函数的定义与使用:
>>> def fun_name(name): ... print name ... >>> fun_name("helllo world") helllo world
abs() 绝对值
round() 四舍五入
math.floor() 取整 ,需要导入math
math.ceil() 进一取整
math.sqrt() 平方根
省略模块名称的方法:
from match import ceil ceil(32.33) 33
cmath库处理虚数:
>>> import cmath >>> cmath.sqrt(-1) 1j
str和repr:
>>> print(str("hello \n hello")) hello hello >>> print(repr("hello \n dedeidj")) 'hello \n dedeidj'
长字符串:忽略转义字符,可以包含特殊字符
>>> '''hello \ndeuhd''' 'hello \ndeuhd' >>> """deuwgfueh\ndjeiwdu\t&#%^&""" 'deuwgfueh\ndjeiwdu\t&#%^&'
原始字符串:在字符串之前加上“r”,如果原始字符串的结尾也是斜杠只能用连接字符串的方法
>>> print(r'c:\demo\hello' '\\') c:\demo\hello\