codewar python 遺忘點

一、計算字符串中特定字符串出現的次數

s = 'this is a new technology,and I want to learn this.'  
print(s.count('this', 0, len(s)))     #目標字符串區分大小寫

二、數字左邊補0的方法,字符串補空格

#python中有一個zfill方法用來給字符串前面補0,很是有用
n = "123"
s = n.zfill(5)
assert s == "00123"
#zfill()也能夠給負數補0
n = "-123"
s = n.zfill(5)
assert s == "-0123"
#對於純數字,咱們也能夠經過格式化的方式來補0
n = 123
s = "%05d" % n
assert s == "00123"

#rjust,向右對其,在左邊補空格
s = "123".rjust(5)
assert s == " 123"
#ljust,向左對其,在右邊補空格
s = "123".ljust(5)
assert s == "123 "
#center,讓字符串居中,在左右補空格
s = "123".center(5)
assert s == " 123 "

三、列表推導式的if...else寫法

#該函數將輸入字符串每一個單詞首字母移到單詞末尾並加上「ay」,最後推導式if...else 寫法
def pig_it(text):
    #your code here
    temp = [c for c in text.split(" ") if c != ""]
    return " ".join([c[1:]+c[0]+"ay" if c[-1].isalpha() else c for c in temp])
相關文章
相關標籤/搜索