day 3 - 資料型別練習
1.有變數 name = " aleX leNB " 完成如下操作
name = " aleX leNB "
# 1) 移除兩端空格
n1 = name.strip()
print(n1)
# 2) 移除左邊的 al
n2 = name[2:]
print(n2)
# 3) 移除左邊的 NB
n3 = name[:-2]
print(n3)
# 4) 移除左邊的 a B
n4 = name[1:-1]
print(n4)
# 5) 判斷是否以 al 開頭
n5 = name.startswith('al')
print(n5)
# 6) 判斷是否以 NB 結尾
n6 = name[-2:]
if n6 == 'NB':
print ('yes')
else:
print ("no")
# 7) 將所有的 l 替換為 p
n7 = name.replace('l','p')
print (n7)
# 8) 將第一個的 l 替換為 p
n8 = name.replace('l','p',1)
print (n8)
# 9) 根據 l 進行分割
n9 = name.split('l')
print (n9)
# 10) 根據第一個 l 進行分割
n10 = name.split('l',1)
print (n10)
# 11) 整體變為大寫
n11 = name.upper()
print (n11)
# 12) 整體變為小寫
n12 = name.lower()
print (n12)
# 13) 首字母 a 大寫
n13 = name.capitalize()
print (n13)
# 14) 判斷 l 出現了幾次
n14 = name.count("l")
print (n14)
# 15) 判斷前 4 位中 l 出現了幾次
#str.count(sub, start= 0,end=len(string))
#start 字串開始搜尋的位置,預設為第一個字元,第一個字元索引值為0
#end 字串中結束搜尋的位置,字元中第一個字元的索引為 0 ,預設為字串的最後一個位置
n15 = name.count("l",0,4)
print (n15)
# 16) 找到 N 對應的索引,如果沒找到則返回 -1
n16 = name.find("N")
print (n16)
# 17) 找到 X le 對應的索引
n17 = name.find("X le")
print (n17)
# 18) 輸出第 2 個字元
n18 = name[1]
print (n18)
name = "aleX leNB"
# 19) 輸出前 3 個字元
n19 = name[:3]
print (n19)
# 20) 輸出後 2 個字元
n20 = name[-2:]
print (n20)
# 21) 獲取第一個 e 對應的索引位置
n21 = name.index("e")
print (n21)
2.有變數 s = "123a4b5c" 完成如下操作
s = "132a4b5c"
#1) 通過切片形成 "123"
s1 = s[0]+s[2]+s[1]
print (s1)
#2) 通過切片形成 "a4b"
s2 = s[3:-2]
print (s2)
#2) 通過切片形成 "1245"
s2 = s[::2]
print (s2)
#3) 通過切片形成 "3ab"
s3 = s[1:-2:2]
print (s3)
#4) 通過切片形成 "c"
s4 = s[-1]
print (s4)
#5) 通過切片形成 "ba3"
s5 = s[-3::-2]
print (s5)
3.使用 while 和 for 迴圈分別列印字串 x = 'asdfer' 中的每個元素
x = 'asdfer' i=0 while i < len(x): print (x[i]) i+=1 for i in x: print (i)
4.實現一個加法計算器
如:5+9 或 5+ 9 或 5 + 9,然後使用分割在進行計算
#num1=int(input("請輸入第一個數:")) #num2=int(input("請輸入第二個數:")) #print (num1+num2) con=input(">>>").split("+") num=0 for i in con: num+=int(i) print(num)
5.計算使用者輸入的內容中有幾個整數
如:content = input('請輸入內容:') sdf456sfsf54f7s4grh8b1
content = input('請輸入內容:') count = 0
for i in content: if i.isdigit(): count+=1 print(count)