Python学习笔记(2)-- if/for/while/字符串操作
if语句
""" if 表达式: 表达式成立 else: 不成立 """ a = 10 b = 20 if a > b: print(a) else: print(b)
for语句
for i in range(0, 10): print(i) else: print("finish")
else:后面语句为结束循环执行,continue导致的结束也会执行
pass:过渡语句(do nothing)
continue:跳过本次循环
break:跳出循环(不会执行else语句)
while语句
i = 0 while i < 4: i += 1 print(i) else: print("finish")
字符串运算符
a = "Peter" b = "Peter" print(a == b) # True print(a is b) # True print(a + b) # PeterPeter print(a * 5) # PeterPeterPeterPeterPeter print("e" in a) # True print("e" not in a) # False
字符串逆序
a = "Peter" b = "Peter" print(a[1]) # e print(a[0:3:1]) # Pet print(a[-1:-4:-1]) # ret [开始:结束:间隔(负数倒序)] print(a[::-1]) # reteP 字符串倒序
字符串大小写
message = "i am a good man" print(message.capitalize()) # I am a good man print(message.title()) # I Am A Good Man print(message.upper()) # I AM A GOOD MAN print(message.lower()) # i am a good man
字符串查找
word = "hello world" print(word.find("l", 0, len(word))) print(word.find("w", 0, len(word))) print(word.rfind("l")) print(word.index("l")) # 找不到不返回异常 print(word.replace("world", "me"))
字符串编码
word = "hello world" print(word.encode("utf-8")) word = word.encode("utf-8") print(word.decode("utf -8"))
字符串判断
file = "boy.jpg" print(file.startswith("boy")) print(file.endswith("jpg"))
字符串join/split/count
join用字符串拼接,拼接为字符串则拆开字母,拼接为列表则元素拆开
a = "boy" print("-".join(a)) # b-o-y
split返回列表
b = "b-o-y" print(b.split("-"))
count统计字符串中的字母
word = "hello world" print(word.count("l")) # 3