• String formatting


    BIT502 Fundamentals of Programming : Contents : Topic 2: Programming concepts : Operations and calculations : String formatting

    two solutions to make string formatting easy and to avoid the above situation.

    • a formatted string 

      The formatted string has the following syntax: f: "some_string_with_variable_insertion"  Wherever we are required to insert a variable, we use {name_of_variable}

    • using a placeholder.(use the operator ‘%’ as a placeholder within a string)
    1. age = 23
    2. weight = 84
    3. height = 1.89
    4. name = "John Smith"
    5. formatted_text = f"Hi. My name is {name}. I am {str(age)} years old. My weight is {str(weight)}Kg and height is {str(height)}m"
    6. print(formatted_text)

    Output:

    Hi. My name is John Smith. I am 23 years old. My weight is 84Kg and height is 1.89m

    1. name = "Marsha"
    2. age = 47
    3. height = 1.63
    4. message1 = "My name is %s." % name # %s is a string placeholder inside the string. Note that the % outside the string
    5. #indicates which data to be replaced against the placeholder. The data type should
    6. #match the placeholder (in this case %s is for string and the variable name is string)
    7. message2 = "I am %d years old" % age # %d is for integer
    8. message3 = "My height is %g m." % height # %f is for float
    9. #For multiple insertion
    10. big_message = "My name is %s. I am %d years old and my height is %g metres." % (name,age,height)
    11. print(message1)
    12. print(message2)
    13. print(message3)
    14. print(big_message)

    Output

    My name is Marsha.

    I am 47 years old

    My height is 1.63 m.

    My name is Marsha. I am 47 years old and my height is 1.63 metres.

    1. name = "Sarah"
    2. number_courses = 3
    3. easy_course = "BIT502"
    4. message1 = "%s is enrolled in %d courses." % (name,number_courses)
    5. message2 = f"Hi there! {message1} The easiest course is {easy_course}"
    6. print(message2)

    Output

    Hi there! Sarah is enrolled in 3 courses. The easiest course is BIT502

  • 相关阅读:
    Kubernetes的容器批量调度引擎 Volcano
    一款.NET开源的i茅台自动预约小助手
    【无标题】
    【牛牛前端面试每天练】一,HTML与CSS专项
    【开发技术】SpingBoot数据库与持久化技术,JPA,MongoDB,Redis
    Java——list的四种遍历
    设计模式个人理解——工厂模式
    Blazor Wasm 身份验证和授权之 OpenID 与 OAuth2
    两日总结十六
    把第三方jar引入到maven中
  • 原文地址:https://blog.csdn.net/hnanxihotmail/article/details/127598277