1. 程式人生 > >python入門8 字串拼接、格式化輸出

python入門8 字串拼接、格式化輸出

字串拼接方式

   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))