iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 7
0
自我挑戰組

30天學會Python系列 第 7

Python - 數字、字串

Hello World

if name == 'main':
在 python 中常常看到下列寫法,是用來判斷該檔案是直接被執行或是被當成 module import 的

if __name__ == '__main__':
    ...
    ...

&http://technology-sea.blogspot.com/2012/03/python-name-import.html

Numbers

數字類型

  • int
  • float
  • complex

運算子

  • + - * / 加減乘除
  • // 無條件捨去除法
  • % 餘數
  • ** 次方

Built-in function

  • abs(x) 絕對值
  • int(x) 將x轉型為整數
  • float(x) 將x為浮點數
  • pow(x,y) x的y次方

String

符號

  • ' ' 單引號
  • " " 雙引號
  • """ """ 三引號 (文本)
    PS: 使用單引號時若要輸出單引號,須輸入\'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s)  # with print(), \n produces a new line
First line.
Second line.

特殊字元

  • ' 單引號
  • \t tab
  • \r\n 換行符號 return

原始字串符
r'C:\some\name'

運算子

"abc" + "def"
"abc"*3 + "def"

支援index取值

s = 'abcdefghijklmn'
s[2] #第三個字元
s[-1] #倒數第一個字元

Slice [開始:結束:step]

s = 'abcdefghijklmn'
s[0:6:2] #[開始:結束:step]

string format
print(name + " is " + age + " year's old.") 改寫為 string format
三種寫法:
"%s..."%(變數)

name  = "Jack"
age = "17"
"%s is %s year's old."%(name, age)

"{}...".format(變數)

name  = "Jack"
age = "17"
"{} is {} year's old.".format(name, age)

f"{變數}..."

name  = "Jack"
age = "17"
message = f"{name} is {age} year's old."

Built-in function
len(s)
dir(s)

string method
更多字串的方法可以參考這裡


上一篇
Python環境設定 Part3 - VS Code簡介
下一篇
Python - Data structure、list列表
系列文
30天學會Python30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言