03 python 初学(字符格式化输出)

时间:2023-03-09 16:01:22
03 python 初学(字符格式化输出)
#_author: lily
#_date: 2018/12/16 name = input("your name: ")
age = input("your age: ") #print(name, age)
"""上面的输出格式并不是想要的"""
msg = """
------------ Info of %s -----------
name: %s
age: %s
------------ END ------------------
""" %(name,name,age)
print(msg)

我们想要输出一串字符,但是在这串字符中又包含变量。

先用 %s 来占位。 s是string的缩写

%d    d = digital 整数

%f    f = float

接着在这个字符串后面加一个 %(),括号里面的内容就是一一对应每个占位符所表示的的变量。

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'

也可以设置参数:

print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))

# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site)) # 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的

也可以传入对象:

#!/usr/bin/python
# -*- coding: UTF-8 -*- class AssignValue(object):
def __init__(self, value):
self.value = value
my_value = AssignValue(6)
print('value 为: {0.value}'.format(my_value)) # "0" 是可选的

1. 判断输入的是否为数字,可以使用 .isdigital() 这个函数

2. 如果满足某条件后,想终止程序,使用 exit("............") 语句