Python study notes (2) - if / for / while / String operations

Python study notes (2) - if / for / while / String operations


 

The if statement

"""
if expression:
    Expression is established
else:
    invalid
"""
a = 10
b = 20
if a > b:
    print(a)
else:
    print(b)

for statement

for i in range(0, 10):
    print(i)
else:
    print("finish")

else: behind the statement to end the loop execution, execution will lead to the end continue

pass: the transition statement (do nothing)

continue: skip this cycle

break: out of the loop (not execute the else statement)


 

while statement

i = 0
while i < 4:
    i += 1
    print(i)
else:
    print("finish")

String operators

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

String in reverse order

= A " Peter " 
B = " Peter " 
Print (A [. 1])              # E 
Print (A [0:. 3:. 1])          # the Pet 
Print (A [-1: -4: -1])       # RET [Start : end: interval (negative descending)] 
Print (A [:: -. 1])           # retep string reverse

String case

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

String Find

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"))

String encoding

word = "hello world"
print(word.encode("utf-8"))
word = word.encode("utf-8")
print(word.decode("utf -8"))

Analyzing string

file = "boy.jpg"
print(file.startswith("boy"))
print(file.endswith("jpg"))

String join / split / count

join a string concatenation, the open letter string of splicing, the splicing element is disassembled listing

a = "boy"
print("-".join(a))  # b-o-y

split Back to list

b = "b-o-y"
print(b.split("-"))

count statistics string of letters

word = "hello world"
print(word.count("l"))    # 3

 

Guess you like

Origin www.cnblogs.com/Epir/p/12613684.html