python入門8 字符串拼接、格式化輸出
阿新 • • 發佈:2018-11-04
格式化 輸出 print ftime inpu 連接 port ack imp
字符串拼接方式
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))
#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))
python入門8 字符串拼接、格式化輸出