Python_eval()

 1 '''
 2 eval()用来把任意字符串转化为Python表达式并进行求值
 3 '''
 4 print(eval('3+4')) #计算表达式的值
 5 a=3
 6 b=4
 7 print(eval('a+b'))  #这时候要求变量a和b已存在
 8 import math
 9 eval('help(math.sqrt)')
10 # Help on built - in function sqrt in module math:
11 # sqrt(...)
12 #     sqrt(x)
13 #
14 #     Return the square root of x.
15 print(eval('math.sqrt(3)'))
16 #eval('aa') 此处使用将报错,aa并未被定义
17 """在Python 3.x中,input()将用户的输入一律按字符串对待,如果需要将其还原为本来的类型,可以使用内置函数eval(),有时候可能需要配合异常处理结构"""
18 # x=input()
19 # print(x)
20 # print(eval(x))
21 # x=input()
22 # print(eval(x))
23 # x=input()
24 # print(x)
25 # try:
26 #     print(eval())
27 # except:
28 #     print('wrong input')
29 # a=input('Please input a value')
30 
31 '''
32 关键字 in:与列表、元组、集合一样,也可以使用关键字in和not in 来判断一个字符串是否出现在另一个字符串中,返回True或False
33 '''
34 print('a' in 'abcd')
35 # True
36 print('ab' in 'abcde')
37 # True
38 print('ac' in 'abcd')
39 # False
40 #example:对用户输入进行检查
41 words = ('测试','非法','暴力')
42 test = input('请输入')
43 for word in words:
44     if word in test:
45         print('非法')
46         break
47 else:
48     print('正常')
49 #下面的代码则可以用来测试用户输入中是否有敏感词,如果有就把敏感词替换为3个***
50 words = ('测试','非法','暴力','')
51 text = '这句话里含有非法内容'
52 for word in words:
53     if word in text:
54         text=text.replace(word,'***')
55 print(text)
56 # 这句***里含有***内容
57 
58 '''
59 startswith(),endswith()
60 这两个方法用来判断字符串是否以指定字符串开始或结束,可以接收两个整数参数来限定字符串的检测范围
61 '''
62 s='Beautiful is better than ugly.'
63 print(s.startswith('Be'))  #检测整个字符串
64 print(s.startswith('Be',5))  #检测指定范围的起始位置
65 print(s.startswith('Be',0,5))   #指定检测范围的起始和结束位置
66 '''另外,这两个方法还可以接收一个字符串元组作为参数来表示前缀或后缀,例如,下面的代码可以列出指定文件夹下所有扩展名为bm、jpg、gif的图片'''
67 # import os
68 # [filename for filename in os.listdir(r'/Users/c2apple/Documents') if filename.endswith('.bmp','.jpg','.png')]
原文地址:https://www.cnblogs.com/cmnz/p/6959143.html