Python 資料型態(字串篇)

by yenchialu

字串代表著以文字與符號為主的資料型態,在Python可以當作一種集合或者矩陣來看待,字串裡的每個文字對映著一個位置編號,最左邊的起始位置為0,開始往後數,空格與符號都算在內。

A = "hello, how are you?"

#使用len()函數,取得字串長度
print (len(A))

#取得第0個位置的值
print (A[0])

#取得最後一個位置的值
print (A[-1])

#取得第9個位置的值
print (A[9])
#輸出結果
>>> 19
    h
    ?
    w

切割或合併字串

除了能取值,字串也能像積木般做不一樣的組合。

切割字串

A = "Good luck"

#取A的字串,第0個位置到第4個位置(第5個位置不包含)
print (A[:5])

#取A的字串,第2個位置到最後一個位置
print (A[2:])

#取A的字串,從倒數第二個位置到倒數第5個位置
print (A[-6:-2])
#輸出結果
>>> Good 
>>> od luck
>>> d lu

組裝字串

A = "Good luck"
B = "Good morning"

C = A+B
D = A[2:7]+B[-8:-2]
print (C)
print (D)

#輸出結果
>>> Good luckGood morning
>>> od lu morni

format組裝字串

除了上面範例組裝字串的方式,還有一個正規的函數方式來組裝字串。

#單一字串填入
age = 18
information = "My name is Robert, and I am {}"
print(information.format(age))
#輸出結果
>>> My name is Robert, and I am 18

這個函式也接受多個參數匯入的方式,見以下範例

height = 180
weight = 70
sport = "badmintion"
introduction = "My height is {} and my weight is {} kg. My favorite sport is {}."
print(introduction.format(height, weight , sport))
#輸出結果
>>> My height is 180 and my weight is 70 kg. My favorite sport is badmintion.

其他常見用法

英文大小寫

A="Jerry"

#全體大寫
print(A.upper())

#全體小寫
print(A.lower())
>>> JERRY
    jerry

Python 入門學習系列文章

  1. PYTHON 基本語法
  2. PYTHON 資料型態(概念介紹篇)
  3. PYTHON 資料型態(數字篇)
  4. PYTHON 資料型態(字串篇)
  5. PYTHON 資料型態(LIST)
  6. PYTHON 資料型態(DICT)
  7. PYTHON 資料型態(BOOLEANS)
  8. PYTHON 條件判斷算式(IF,ELIF,ELSE)
  9. PYTHON WHILE 迴圈
  10. PYTHON FOR 迴圈
  11. PYTHON DEF 函式
  12. PYTHON MODULES 模組

You may also like

Leave a Comment