python 基础9-拼接

参考文档:

https://zhuanlan.zhihu.com/p/90439125

1、百分号-字符串拼接:

  1. %s 用法

    print("I am %s my hobby is %s" %("lzf","play"))
   ==
    print("I am {},my hobby is {}".format("lzf","play"))

  2.  %s 可以传任意值    

    print("I am %s my hobby is %s" %("lzf","[1.2]"))

  3. %d 只能传数字
    print("I age %d" %(18))

       4. %f 打印浮点数,默认保留 6位小数
    print("percent %f" % 99.123456789)

  5. 保留指定位数,如 %.2f"
    print("percent %.2f" % 99.123456789)

2、sep = " " 拼接

  print("root","pwd","root",sep=" :")

3、format-字符串格式化

  1. 传值为 字典
    tp1 = "I am {name},age{age},hobby{hobby}".format(**{"name":"alex","age":18,"hobby":"play"})
    print(tp1)

  2. 传值为固定类型 :s-字符串,:d--int类型,:f--浮点类型
    tp1 = "I am {:s},age{:d},mokey{:.2f}".format("alex",18,88.123456)
    print(tp1)

 4、案例:

def test_1():
    a = '1'
    b = '2'
    print("Hello, %s %s. " % ("first_name", "last_name"))
    print ("Hello, %s %s. " % (a,b))

    print ("Hello,{}. You are {}.".format ("Alex", "18"))
    print ("Hello,{}. You are {}.".format (a,b))

    print (f"Hello,{a}. You are {b}.")
    print (f"Hello,{a}. You are {b}.")

def test_2():
    comedian = {'name': 'Eric Idle', 'age': 74}

    print ("The comedian is {name}, aged {age}.".format(name=comedian["name"],age=comedian["age"]))
    print ("The comedian is {name}, aged {age}.".format (**comedian))

    print(f"The comedian is {comedian['name']}, aged {comedian['age']}.")

# 备注:% 不支持字段类型,.format与f 都支持字典, f运行最快
原文地址:https://www.cnblogs.com/zhuanfang/p/12520553.html