如何在Python中評估字串並返回物件?


透過使用Python中的`eval()`函式,我們可以評估字串並返回一個Python物件。`eval()`是Python的內建函式,它透過將字串解析為程式碼表達式來評估字串引數。

語法

eval(expression[, globals[, locals]])

引數

  • 表示式:將被評估為Python表示式的字串。

  • globals:可選引數,是一個包含全域性引數的字典。

  • locals:可選引數,是一個包含區域性引數的字典。

  • 返回值:返回從表示式計算的結果。

如果字串包含算術表示式

如果我們將包含算術表示式的字串傳遞給`eval()`函式,它首先解析表示式,然後對其進行評估,最後返回一個已評估的Python物件。

示例

var = 100
string_EXP_1 = "2*4"
string_EXP_2 = "var + 20"

print("string expression 1: ", string_EXP_1)
print("string expression 2: ", string_EXP_2)

# use the eval method 
result_1 = eval(string_EXP_1)
result_2 = eval(string_EXP_2)

print("Output for Expression 1: ", result_1)
print("Output for Expression 1: ", result_2)

輸出

string expression 1:  2*4
string expression 2:  var + 20
Output for Expression 1:  8
Output for Expression 1:  120

正如我們在上面的示例中看到的,`eval()`成功地評估了由算術表示式組成的字串,並返回了一個整數物件。我們還可以看到該函式訪問了全域性變數x。

如果字串包含列表/元組

`eval()`函式還可以評估包含列表/元組的字串。這意味著它根據字串資料返回列表/元組物件。

示例

string = "1, 2"

print("Input String: ", string)
print('type', type(string))

# apply the eval method 
result = eval(string)

print("Output : ", result)
print("Output object type: ", type(result))

輸出

Input String: 1, 2
type <class 'str'>
Output :  (1, 2)
Output object type:  <class 'tuple'>

輸入字串包含兩個以逗號分隔的元素,在Python中,以逗號分隔的值被視為元組的元素。因此,上面的示例在應用`eval()`函式後返回了一個元組物件。

示例

與之前的示例類似,`eval()`函式評估了字串並返回了一個列表物件。

string = "[45, 9, 16]"

print("Input String: ", string)
print('type', type(string))

# apply the eval method 
result = eval(string)

print("Output : ", result)
print("Output object type: ", type(result))

輸出

Input String:  [45, 9, 16]
type <class 'str'>
Output :  [45, 9, 16]
Output object type:  <class 'list'>

如果字串包含列表推導式表示式

`eval()`函式還可以評估列表推導式表示式,如果輸入字串包含列表推導式表示式,則返回一個Python列表物件。

示例

`eval`函式成功地評估了列表推導式表示式並返回了一個Python列表物件。

string = '[a*2 for a in range(5)]'

print("Input String: ", string)
print('type', type(string))

# apply the eval method 
result = eval(string)

print("Output : ", result)
print("Output object type: ", type(result))

輸出

Input String:  [a*2 for a in range(5)]
type <class 'str'>
Output :  [0, 2, 4, 6, 8]
Output object type:  <class 'list'>

如果字串包含Python字典

如果字串包含Python字典,則`eval()`方法將返回一個原始的Python字典物件。

示例

String_dict = "{'One': 1, 'two': 2, 'three': 3}"
print("String represented dictionary: ",String_dict)
print(type(String_dict))

# use the eval method 
dict_ = eval(String_dict)
print("Output: ", dict_)
print(type(dict_))

輸出

String represented dictionary:  {'One': 1, 'two': 2, 'three': 3}
<class 'str'>
Output:  {'One': 1, 'two': 2, 'three': 3}
<class 'dict'>

正如我們在上面的輸出塊中看到的,`eval()`函式返回一個Python字典物件。

更新於:2023年8月23日

993 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告