Chinaunix
标题:
[求助]函数中打印变量名
[打印本页]
作者:
hjfeng1988
时间:
2015-04-29 11:31
标题:
[求助]函数中打印变量名
#!/usr/local/bin/python
line1=[1]
line2=[1,'','a']
line3=['b','c']
def linenum(line):
if len(line) >= 2:
if line[1] == '':
print '%s[1] is empty' % line
else:
print '%s[1] = %s' % (line,line[1])
else:
print '%s[1] is none' % str(line)
linenum(line1)
linenum(line2)
linenum(line3)
复制代码
root@10:~/py # python num.py
[1][1] is none
[1, '', 'a'][1] is empty
['b', 'c'][1] = c
复制代码
我希望输出的结果是:
line1[1] in none
line2[1] is empty
line3[1] = c
作者:
liujinz
时间:
2015-05-04 09:20
本帖最后由 liujinz 于 2015-05-04 09:20 编辑
你这里的[1]都被认为是格式串的一部分,不会被认为是列表的下标的。
作者:
substr函数
时间:
2015-05-04 13:38
一部分
line1[1] is none
line2[1] is empty
line3[1] = c
line4[1] = c
复制代码
line1 = [1]
line2 = [1,'','a']
line3 = ['b','c']
line4 = ['b','c']
def linenum(line):
for k, v in globals().iteritems():
if id(v) == id(line):
name = k
break
if len(line) >= 2:
if line[1] == '':
print '%s[1] is empty' % name
else:
print '%s[1] = %s' % (name,line[1])
else:
print '%s[1] is none' % name
linenum(line1)
linenum(line2)
linenum(line3)
linenum(line4)
复制代码
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2