溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python基礎 print()的使用

發(fā)布時間:2020-08-09 15:53:12 來源:網(wǎng)絡 閱讀:1142 作者:圣嬰大王 欄目:編程語言

Print:打印標準輸出的函數(shù)
格式:print()
print()函數(shù)有三個參數(shù)

  1. value用戶需要輸出的信息
  2. sep多個要輸出信息之間的分隔符,默認是空格
  3. end輸出信息結尾處的默認添加的符號,默認為換行符

函數(shù)參數(shù)使用舉例:

>>>num1=2
>>>str1='words'
>>>print(num1,str1)
2 words

默認2與words之間有一個空格,輸出完成之后有一個回車
使用了@作為分割符

>>>print(num1,str1,sep='@')
2@words

使用&作為結尾

>>>print(num1,str1,sep='@',end='&')
2@words&

其實print函數(shù)還有一個參數(shù)file,通常print函數(shù)都是stdout方式輸出,但是如果需要將輸出結果重定向到一個文件可以使用file參數(shù)

f=open("d:\\new.txt","w")
for i in range(6):
print("new line",file=f)

此時在d盤更目錄下會自動創(chuàng)建一個new.txt文件,并打印6行new line在其中。

【Case1】

直接輸出打印內容

>>>print("This is a new word.")
This is a new word.

如果內容過長,可以使用\作為換行符

>>>print("This is a new \
word")
This is a new word

【Case2】

使用變量打印內容

>>> a="This is a new word."
>>> print(a)
This is a new word.

【Case3】

使用三引號作為格式打印

>>>str="""
This
is
a
new
word
.
"""
>>>print(str)
This
is
a
new
word
.

【Case4】

除了使用三引號作為格式化輸出,還有兩種格式化輸出的方式%和.format



使用%占位符格式化打印
主要使用的占位符有:
%s 字符串
%r 字符串
%d 十進制整數(shù)
%i 十進制整數(shù)
%f 浮點數(shù)


>>>str1='world'
>>>print('hello %s' %'world')
hello world
>>>print('hello %s' %str1)
hello world
>>>str='abc'
>>>print("%s" %str)
abc
>>> print("%s" %str.title())
Abc
>>>print('hello %r' %str1)
hello 'world'

>>>num1=300
>>>print ('the number is','%d' %num1)
the number is 300
>>>print ('the number is','%i' %num1)
the number is 300
>>> num2=30
>>> name='John'
>>> print('He is %s, he is %d years old.' %(name,num2))
He is John, he is 30 years old.

其它占位符:
%c 單個字符
%b 二進制整數(shù)
%o 八進制整數(shù)
%x 十六進制整數(shù)
%e 指數(shù) (基底寫為e)
%E 指數(shù) (基底寫為E)
%F 浮點數(shù),與上相同
%g 指數(shù)(e)或浮點數(shù) (根據(jù)顯示長度)
%G 指數(shù)(E)或浮點數(shù) (根據(jù)顯示長度



使用format()方法格式化打印


>>> str='''
Username={uname}
Id={id}
Phone={tel}
'''.format(uname='Jone',id='123',tel='138***')
>>> print(str)
Username=Jone
Id=123
Phone=138***
>>> str2="{0}".format("abc")
>>> print(str2)
abc
>>> str='''
username={0}
Id={1}
Phone={2}
'''.format('Jone','123','138***')
>>> print(str)
username=Jone
Id=123
Phone=138***

【Case5】

轉義字符
常用轉義字符:
/t 輸出一個橫向指標符
/n 輸出一個換行符
/v 輸出一個縱向制表符
/f 輸出一個換頁
/r 輸出一個回車


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI