iT邦幫忙

1

Day4 - [再不學python我要被世界淘汰了]Numbers/Casting/Strings

  • 分享至 

  • xImage
  •  

Day1~Day3在我的方格子 : https://vocus.cc/user/6581c332fd897800011ce225

Numbers

Random Number

python沒有random()這個方程式

所以要在一開始import進去

import random
print(random.randrange(1, 100))

Casting(型別轉換)

int()

把資料轉成整數。
可以把整數、浮點數(會捨去小數點)、或「表示整數的字串」轉成 int。

float()

把資料轉成浮點數。
可以處理整數、浮點數、或「表示數字的字串」。

str()

把資料轉成字串。
幾乎什麼型態都能轉成字串。
EX :
https://ithelp.ithome.com.tw/upload/images/20250606/20173411KBBo7SBC3u.png

Strings (字串)

字串可以用單引號 '...' 或**雙引號 "..." **包起來。

Quotes Inside Quotes (字串內的引號)

print("Today is hot !")           # 字串外面是雙引號,裡面用單引號沒問題
print("She is called 'Debby'")  # 外面雙引號,裡面單引號沒問題
print('She is called "Debby"')  # 外面單引號,裡面雙引號沒問題

output :

Today is hot !
She is called 'Debby'
She is called "Debby"

補充:如果內外都是同一種引號怎麼辦?

你可以用跳脫字元(escape character)\ 來避免語法錯誤

簡單來說就是用\保護單引號'或是雙引號"

EX :

print('It\'s hot')      # 單引號內還是要用單引號時,加 \ 
print("She is called \"Debby\"") # 雙引號內再用雙引號時,加 \

output :

It's hot
She is called "Debby"

Multiline Strings (多行字串)

用法

如果要讓字串跨越多行,可以用三個雙引號 """...""" 或三個單引號 '''...''' 把內容包起來。

  • 這種寫法常用於:
    1.多行說明文字(像註解)
    2.格式化輸出
    3.長篇內容
    用三引號建立的多行字串,內容裡的「換行」會被保留。
    這種方式很適合直接存放詩詞、程式說明、HTML 片段等。

Strings are Arrays

1. 字串本質 & 索引

  • 字串是「字元陣列」(其實是 Unicode 編碼的字元序列)。
  • Python 沒有獨立的「字元型態」,單一字元也是長度為 1 的字串。
  • 可以用中括號 [] 來取出某個位置的字元,索引從 0 開始。
a = "Hi Debby"
print(a[1])    # 輸出: i (第二個字元)

output :

i

2.Looping Through a String (字串迴圈) for 迴圈最常見、最基礎的寫法與用法!

A.依序拿出字元

可以用 for 迴圈逐字元走訪字串:

for x in "banana":
    print(x)
# 會依序印出 b a n a n a

這裡 "banana" 是一個字串(string),而字串本質上是「字元的序列」。

  • for x in "banana": 就是把 "banana" 這個字串裡的每個字母(字元)一個一個拿出來(依序)。
    每拿出一個字元,就印出(print(x))一次。

B.依序拿出元素

for x in [0,1,2,3,4,5]:
  print(x) 
 
#會依序印出0 1 2 3 4 5 ​

這裡 [0, 1, 2, 3, 4, 5] 是一個「串列」(list),裡面有六個數字。

  • for x in [0, 1, 2, 3, 4, 5]: 就是把這個 list 裡的每個元素一個一個拿出來。
    每拿出一個數字,就印出一次。
    可以等效為 :
for x in range(6):
    print(x)
# 會依序印出 0 1 2 3 4 5

核心概念

  • for x in 某個可迭代物件,就是「把裡面的每一個元素(無論是字元、數字、還是其他東西)都拿出來執行一次 for 迴圈內的內容」。
    P- ython 的 for 迴圈可以遍歷string(每次拿一個字元)、也可以遍歷list(每次拿一個元素)。

3. len(字串長度)

用 len() 取得字串長度(字元數)。

a = "I'm learning Python!"
print(len(a))   # 輸出: 20

4.Check String (檢查子字串)

  • 用 in 檢查某字串是否包含某內容。
  • 用 not in 檢查某字串不包含某內容。
txt = "The best things in life are seafood!"
print("seafood" in txt)  

if "seafood" in txt:
    print("Yes, 'seafood' is present.")
    
    
print("expensive" not in txt) 

if "expensive" not in txt:

		 print("No, 'expensive' is NOT present.")

output :

True
Yes, 'seafood' is present.
True
No, 'expensive' is NOT present.

今天先醬~要來看下禮拜的期末考了~

https://vocus.cc/article/68428090fd89780001661c90


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言