python入门6 字符串拼接、格式化输出

时间:2023-03-09 01:54:56
python入门6 字符串拼接、格式化输出

字符串拼接方式

   1  使用 + 拼接字符串

2  格式化输出:%s字符串 %d整数 %f浮点数 %%输出% %X-16进制 %r-原始字符串

3 str.format()

代码如下:

#coding:utf-8
#/usr/bin/python
"""
2018-11-03
dinghanhua
字符串拼接,格式化输出
"""
import time name = input('input name :') #输入姓名
age = int(input('input age:')) #输入年龄
nowtime = time.strftime('%Y%m%d %H:%M:%S',time.localtime()) #当前时间
'''使用 + 拼接字符串'''
#字符串连接
print('your name is '+name+',\nyour are '+str(age)+' years old. \ntime: '+nowtime)
'''
格式化输出
方式一: %s字符串 %d整数 %f浮点数 %%输出% %X-16进制 %r-原始字符串
方式二: str.format()
'''
#格式化输出
print("""your name is %s,
your are %d years old.
time: %s"""%(name,age,nowtime)) '''浮点数制定输出2位小数; %%输出%'''
percent = 50.5
print('percent is %.2f%%' % percent) #制定浮点数的小数位 '''%X'''
x = 0xf00
print('16进制:0x%X' % x) '''%s,%r的区别'''
print('str is %%s %s' % r'c:\user\local')
print('str is %%r %r' % r'c:\user\local')
# str.format()
str = """your name is {0},
your are {1} years old.
time: {2}"""
print(str.format(name,age,nowtime)) str2 = """your name is {name},
your are {age} years old.
time: {time1}"""
print(str2.format(name=name,age=age,time1=nowtime))