1.抓取字串中的第幾個字
- 實作題:
- 使用者輸入身分字號: G221234567 G101234456
- 代表2為女生,1為男生,可印出身分證字號第2碼為: ? 1或2
2.取字串從第幾個開始~到幾個字結束
3.計算字串長度
4.將字串全轉為小寫、大寫
5.字元取代
6.字串分割為陣列
實作: 整理字串後讀出 data = "0912569369-John-Taipei-09:02"
1.抓取字串中的第幾個字
a = "Hello,world"
print(a[6]) #抓字串的第幾個位置 從0開始算

- 實作題:
- 讓使用者輸入身分字號: G221234567 G101234456
- 代表2為女生,1為男生,可印出身分證字號第2碼為: ? 1或2
a = input("請輸入身分證字號:") #G123852941
print("身分證號碼第2位="+a[1]) #抓字串的第幾個位置 從 0 開始算

2.取字串從第幾個開始~到幾個字結束
#取字串從第幾個開始~到幾個字結束
b = "Hello, World!"
print(b[2:5]) #5的位置結束(不會印出)

3.計算字串長度
可能會用到的地方:
規定使用者只能輸入幾個字的時候,或者使用迴圈時計算資料長度時,等等
a = "Hello, World!"
print(len(a))

4.將字串全轉為小寫、大寫
哪時會用到?
比如讓使用者輸入身分證字號時,可以自動將使用者輸入的第一個字母強制轉成大寫。
或者
我們預設帳號的都是小寫
讓使用者輸入帳號時,這時就可以強制將使用者輸入的字母全都轉成小寫,減少使用者如果輸入大寫時的錯誤。
name = "YirUATSTUdio"
print(name.lower())
name = "YirUATSTUdio"
print(name.upper())

#字元取代
a = "YiruAt, Studio!"
print(a.replace("A", "a")) #Yiruat, Studio!
print(a.replace(", ", "")) #YiruAtStudio!
b = "Hello, World!"
print(b.replace("Hello,", "哈囉!"))#哈囉! World!

6.字串分割為陣列
有些資料會使用 "," 、"、" 、"空格"、"-" ,等等符號來紀錄資料
這時候我們需要把這些字串整理出來,分割字串讓他為陣列,方便我們做使用
a = "Yiru,AtStudio!,123,abc" #只是一串文字
b = a.split(",") #使用,號分割字串 ,變成 陣列 ['Yiru','AtStudio!','123','abc']
print(a)
print(b)
#['Yiru','AtStudio!','123','abc']
#第[0]個位置 Yiru,第[1]個位置 AtStudio! 以此類推
print(b[1]) #AtStudio!
#如果資料是用其他符號 例如: ||
a = "Hello||World!||123||aa"
b = a.split("||")
print(b[2]) #123

6.字串分割為陣列
實作: 整理字串後讀出 data = "0912569369-John-Taipei-09:02"
電話:0912569369
姓名:John
縣市:Taipei
登入時間:09:02

data = "0912569369-John-Taipei-09:02"
b = data.split("-") #分割符號為 "-"
print("電話:"+b[0]) #0912569369
print("姓名:"+b[1]) #John
print("縣市:"+b[2]) #Taipei
print("登入時間:"+b[3]) #09:02
Yiru@Studio - 關於我 - 意如