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)
age = 23
weight = 84
height = 1.89
name = "John Smith"
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"
print(formatted_text)

Output:

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

name = "Marsha"
age = 47
height = 1.63
message1 = "My name is %s." % name         # %s is a string placeholder inside the string. Note that the % outside the string 
                                           #indicates which data to be replaced against the placeholder. The data type should 
                                           #match the placeholder (in this case %s is for string and the variable name is string)
        
message2 = "I am %d years old" % age       # %d is for integer
 
message3 = "My height is %g m." % height   # %f is for float
 
#For multiple insertion
big_message = "My name is %s. I am %d years old and my height is %g metres." % (name,age,height)
 
print(message1)
print(message2)
print(message3)
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.

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

Output

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值