您的位置:首页 > 编程语言 > Python开发

codewar python 遗忘点

2016-12-06 00:00 169 查看

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()也可以给负数补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 "


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])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: