一、计算字符串中特定字符串出现的次数
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])