zoukankan      html  css  js  c++  java
  • 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("............") 语句

  • 相关阅读:
    maven项目,去除jar包中的不想要的依赖关系
    Eclipse:An internal error occurred during: "Build Project". GC overhead limit exceeded
    如何用Maven创建web项目(具体步骤)
    让Jackson JSON生成的数据包含的中文以unicode方式编码
    MySQL存储过程详解 mysql 存储过程
    MySQL SQL Injection(注入)
    撤销Excel工作表保护密码(考勤机报表)
    youtube-dl下载视频
    LSI9240 8i在dos下刷IT直通模式
    制作DOS引导U盘(支持扩展任何dos下的程序)
  • 原文地址:https://www.cnblogs.com/mlllily/p/10127673.html
Copyright © 2011-2022 走看看