自学内容网 自学内容网

Python常用语法汇总(二):if语句、循环、匿名函数、正则表达式

4. if语句

#1
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else: 
        print(car.lower())

car = 'Audi'
car == 'audi' #
返回的是False,区分大小写
car.lower() == 'audi'
if car !="audi" :
    print("car is title")

age = 19
age <= 21 and age >= 15  #

age <20 or age >19   #

car = 'bench'
car in cars     #
检查特定值是否包含在列表中
car not in cars #检查特定值是否不包含在列表中

#2
if age < 18:
    print("You are so young!")
else if age < 25:
    print("You are young!")
else:
    print("Hello uncle!")

#
3
requested_toppings = []
if requested_toppings: #
确定列表非空
    for requested_topping in requested_toppings:
        print("Adding" + requested_topping + ".")
        print("\nFinished making your pizza")
else:
    print("Are you sure you want a plain pizza?")

 

5. 用户输入

message  = input("Tell me something, and I will repeat it back to you:")
print(message)

age = input("How old are you?") #
默认解读为字符串
age = int(age) #使用int()将数字的字符串转换为数值
age >= 18

number = input("Enter a number, and I'll tell you if it's even or odd:")
number = int(number)
if number % 2 == 0:
    print("\nThe number" + str(number) + "is even.")
else:
    print("\nThe number" + str(number) + "is odd.")

6. while循环

#1
current_number = 1
while current_number <=5:

print("current_number")
    current_number +=1
    if current_number == 3:
        break

#
2
number = 0
while number < 10:.0.
    number +=1
    if number % 2 ==0:
        continue
    print(number)

#
3
unconfimed_users = ['alice','brian','candace']
confirmed_users = []
while unconfirmed_users:
    current_user = unconfimed_users.pop() #
删除列表末尾的元素
    print("Verifying user:" + current_user.title())
    confirmed_users.append(current_user)
    print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())


7. 匿名函数lambda,filter

filter_me = [1,2,3,4,5,6,7,8]
result = filter(lambda x: x%2==0,filter_me)
print(*result)

#
短路循环:Map
map_me = ['a','b','c','d','e','f','g']
result1 = map(lambda x:"The letter is %s \n"%x,map_me)
print(*result1)

#
列表解析
all = [1,2,3,4,5,6,7,8,9,10]
print([x for x in all if x%2==0])

#
4
pets = ['dog','cat','dog','rabbit','dog']
while 'dog' in pets:
    pets.remove('dog')


8. 正则表达式
#1. 打印以hy开头的字符
str1 = ['hy haha', 'love haha', 'hymain']
for stri in str1:
    if stri.startswith('hy'):
        print(stri)


#2.
打印以hy开头和结尾的字符
str2 = ['hyhahahy', 'hyhaha', 'hahahy', 'hahahyhaha']
for stri in str2:
    if stri.startswith('hy') and stri.endswith('hy'):
        print(stri)

#3.
判断一个变量名是否以下划线或者字母开头
a1 = 'Hhy'
a2 = '1xhy'
a3 = '_hy'
def judge(a):
    if a[0]=='_' or 'A'<=a[0]<='z':
        print('
合法命名')
    else:
        print('
非法命名')
    return 0;
judge(a1)
judge(a2)
judge(a3)
#
可以看到,每次匹配都要单独完成,可将其做成一个规则:正则表达式
# 正则表达式:使用单个字符串来描述匹配一系列符合某个句法规则的字符串;是对字符串操作的一种逻辑公式
# 匹配过程:一次拿出表达式和文本中的字符比较,若每个字符都能匹配,则匹配成功。
# import repython正则表达式模块
# 步骤:先用re.compile()生成pattern对象->再用pattern的匹配方法匹配出结果字符串
# 1.1 1的正则方法 
import re
str3 = 'hy love XLh'
pattern = re.compile(r'hy',re.I)  #r
是为了避免\为转义符,re.I是忽视大小写
mastr = pattern.match(str3)
mastr.group()
mastr.span()
mastr.string

#
正则表达式语法
.     :匹配任意字符(除了\n)
[]    :匹配字符集
\d\D:匹配数字或非数字
\s\S:匹配空白或非空白
\w\W:匹配单词字符[a-zA-Z0-9]h或非单词字符
*        :匹配前一个字符0次或无限次
+        :匹配前一个字符1次或无限次
?        :匹配前一个字符0次或一次
{m}{m,n}:匹配前一个字符m次或mn
*?或者+?或者?? :匹配模式变为非贪婪(尽可能少匹配字符)
^     :匹配字符串开头
$     :匹配字符串结尾
\A\Z:指定的字符串必须出现在开头或结尾
|         :匹配左右任意表达式
(ab)      :括号中表达式作为一个分组
\<number> :引用编号为number的分组匹配到的字符串
(?P(name)):分组起一个别名
(?P=name) :引用别名为name的分组匹配字符串

re.match(r'^[\w]{4,10}@163.com$','imooc@163.com')  # 匹配以@163.com结尾且长度为410的字符开头的邮箱
re.match(r'^[\w]{4,10}@(163|126.com)$','imooc@126.com')  # 匹配以@163.com或者@126.com结尾且长度为410的字符开头的邮箱
re.match(r'\Aimooc[\w]*','imoocpython')  # 匹配以imooc开头的字符串
re.match(r'[1-9]?\d$|100','99')  # 匹配数字0-100


原文地址:https://blog.csdn.net/Trisyp/article/details/136540136

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!