Python import() 函数
描述
import() 函数用于动态加载类和函数 。
如果一个模块经常变化就可以使用 import() 来动态载入。
语法
import 语法:
import(name[, globals[, locals[, fromlist[, level]]]])
Python format 格式化函数
Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
基本语法是通过 {} 和 : 来代替以前的 % 。
format 函数可以接受不限个参数,位置可以不按顺序。
实例
“{} {}”.format(“hello”, “world”) # 不设置指定位置,按默认顺序
‘hello world’
“{0} {1}”.format(“hello”, “world”) # 设置指定位置
‘hello world’
“{1} {0} {1}”.format(“hello”, “world”) # 设置指定位置
‘world hello world’
实例
class AssignValue(object):
def __init__(self, value):
self.value = value
my_value = AssignValue(6)
print('value 为: {0.value}'.format(my_value)) # "0" 是可选的
Python str() 函数
描述
str() 函数将对象转化为适于人阅读的形式。
语法
以下是 str() 方法的语法:
class str(object=’’)
参数
object – 对象。
返回值
返回一个对象的string格式。
实例
s = ‘RUNOOB’
str(s)
‘RUNOOB’dict = {‘runoob’: ‘runoob.com’, ‘google’: ‘google.com’};
str(dict)
“{‘google’: ‘google.com’, ‘runoob’: ‘runoob.com’}”
Python sum() 函数
描述
sum() 方法对序列进行求和计算。
语法
以下是 sum() 方法的语法:
sum(iterable[, start])
参数
iterable – 可迭代对象,如:列表、元组、集合。
start – 指定相加的参数,如果没有设置这个值,默认为0。
返回值
返回计算结果。
实例
sum([0,1,2])
3sum((2, 3, 4), 1) # 元组计算总和后再加 1
10sum([0,1,2,3,4], 2) # 列表计算总和后再加 2
12