1. 通过位置
>>> "{0} {1}".format("hello", "world") 'hello world' >>> "{} {}".format("hello", "world") 'hello world' >>> "{1} {0} {1}".format("hello", "world") 'world hello world'
2. 通过关键字
>>> "I am {name}, age is {age}".format(name="huoty", age=18) 'I am huoty, age is 18' >>> user = {"name": "huoty", "age": 18} >>> "I am {name}, age is {age}".format(**user) 'I am huoty, age is 18'
3. 通过对象属性
>>> class User(object): ... def __init__(self, name, age): ... self.name = name ... self.age = age ... ... def __str__(self): ... return "{self.name}({self.age})".format(self=self) ... ... def __repr__(self): ... return self.__str__() ... ... >>> user = User("huoty", 18) >>> user huoty(18) >>> "I am {user.name}, age is {user.age}".format(user=user) 'I am huoty, age is 18'
4. 通过下标
>>> names, ages = ["huoty", "esenich", "anan"], [18, 16, 8] >>> "I am {0[0]}, age is {1[2]}".format(names, ages) 'I am huoty, age is 8' >>> users = {"names": ["huoty", "esenich", "anan"], "ages": [18, 16, 8]} >>> "I am {names[0]}, age is {ages[0]}".format(**users)
5. 指定转换
“!r” 对应 repr(); “!s” 对应 str(); “!a” 对应 ascii()。 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2"
类似
a = "a" "%s"%a >>>"a" "'%s'"%a >>>"'a'"
字符串对齐:
str.rjust(width[, fillchar]) 右对齐
str.ljust(width[, fillchar]) 左对齐
str.center(width[, fillchar]) 中间对齐