Hướng dẫn convert string to command python - chuyển đổi chuỗi thành lệnh python
Tránh exec và evalSử dụng exec và eval trong Python rất cau mày.Có những lựa chọn thay thế tốt hơnTừ câu trả lời hàng đầu (nhấn mạnh của tôi): Show
Từ các lựa chọn thay thế đến Exec/Eval?
Nó không thành ngữTừ http://lucumr.pocoo.org/2011/2/1/exec-in-python/ (nhấn mạnh của tôi)
Nó nguy hiểmTừ http://nedbatchelder.com/blog/201206/eval_reallly_is_dangero.html (nhấn mạnh của tôi)
Thật khó để đọc và hiểuTừ http://stupidpythonideas.blogspot.it/2013/05/why-evalexec-is-bad.html (nhấn mạnh của tôi):
Xem thảo luận Cải thiện bài viết Lưu bài viết Xem thảo luận Cải thiện bài viết Lưu bài viết Đọc Input: code = """ a = 6+5 print(a)""" Output: 11 Explanation: Mind it that "code" is a variable and not python code. It contains another code, which we need to execute. Input: code = """ def factorial(num): for i in range(1,num+1): fact = fact*i return fact print(factorial(5))""" Output: 120 Explanation: On executing the program containing the variable in Python we must get the result after executing the content of the variable. Bàn luậnexec() function to solve the code contained inside a variable. exec() function is used for the dynamic execution of Python code. It can take a block of code containing Python statements like loops, class, function/method definitions and even try/except block. This function doesn’t return anything. The code below solves the problem and explains the exec() function. Python31201 1202 1203 1204 1205 1203 exec 1208 1209 Output: 120 Bài viết này được đóng góp bởi Chinmoy Lenka. Nếu bạn thích GeekSforGeeks và muốn đóng góp, bạn cũng có thể viết một bài viết bằng Write.GeekSforGeek.org hoặc gửi bài viết của bạn. Xem bài viết của bạn xuất hiện trên trang chính của GeekSforGeek và giúp các chuyên viên máy tính khác. Xin vui lòng viết nhận xét nếu bạn tìm thấy bất cứ điều gì không chính xác hoặc bạn muốn chia sẻ thêm thông tin về chủ đề được thảo luận ở trên. & NBSP;Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using
write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks. Làm thế nào để bạn chuyển đổi một chuỗi thành một lệnh trong Python?Nếu bạn muốn thực thi các câu lệnh Python, bạn có thể sử dụng Exec (String).Ví dụ: >>> my_code = 'In "Hello World!"' >>> exec (my_code) Xin chào thế giới!exec(string). For example, >>> my_code = 'print "Hello World!"' >>> exec(my_code) Hello World!
Làm thế nào để bạn thực hiện một chuỗi?Cho một vài dòng mã bên trong một biến chuỗi và thực thi mã bên trong chuỗi.Ví dụ: Đầu vào: CODE = "" "A = 6+5 In (a)" "" Đầu ra: 11 Giải thích: Hãy nhớ rằng "mã" là một biến và không phải là mã python.. Examples: Input: code = """ a = 6+5 print(a)""" Output: 11 Explanation: Mind it that "code" is a variable and not python code. |