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')]
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息