1、计算字符串中特定字符串出现的次数
s = 'this is a new technology,and I want to learn this.' print(s.count('this', 0, len(s))) #目标字符串区分大小写
2、数字左边补0的方法,字符串补空格
#python中有一个zfill方法用来给字符串前面补0,非常有用n = "123"s = n.zfill(5)assert s == "00123"#zfill()也可以给负数补0n = "-123"s = n.zfill(5)assert s == "-0123"#对于纯数字,我们也可以通过格式化的方式来补0n = 123s = "%05d" % nassert 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 "
3、列表推导式的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])