Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách chuyển tất cả đối số hàm thành chữ thường trong Python

Sử dụng module inspect để lấy tên các tham số của hàm, sau đó chuyển thành chữ thường.

Ví dụ

import inspect

def foo(ARG1, ARG2):
    pass

# Lấy danh sách tên tham số
args = inspect.getargspec(foo)[0]  # Python 2
# Python 3: inspect.getfullargspec(foo).args

# Chuyển thành chữ thường
lower_args = [arg.lower() for arg in args]
print(lower_args)

Đầu ra

['arg1', 'arg2']

Lưu ý phiên bản Python 3

import inspect

def foo(ARG1, ARG2):
    pass

args = inspect.getfullargspec(foo).args
print([a.lower() for a in args])

inspect.getfullargspec() trả về named tuple chứa args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations.