我不知道在return None不需要的时候跳过是不好的方式.
例:
def foo1(x):
if [some condition]:
return Baz(x)
else:
return None
def foo2(x):
if [some condition]:
return Baz(x)
bar1 = foo1(x)
bar2 = foo2(x)
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,当条件为假时,函数将返回None.
我怎样才能完成这样的工作:
def get_foo(someobject, foostring):
return someobject.foostring
Run Code Online (Sandbox Code Playgroud)
IE:
如果我这样做get_foo(obj, "name")应该是调用obj.name(请参阅输入字符串,但我称之为attritube.
谢谢
对于程序菜单中的"q"(退出)选项,我有以下代码:
elif choice == "q":
print()
Run Code Online (Sandbox Code Playgroud)
这是可行的,直到我把它放在一个无限循环,这不断打印空行.有没有可以退出程序的方法?另外,你能想到另一种解决方案吗?
我想用它tempfile.NamedTemporaryFile()来写一些内容然后打开那个文件.我写了以下代码:
tf = tempfile.NamedTemporaryFile()
tfName = tf.name
tf.seek(0)
tf.write(contents)
tf.flush()
Run Code Online (Sandbox Code Playgroud)
但我无法打开此文件,并在记事本或类似的应用程序中查看其内容.有没有办法实现这个目标?为什么我不能这样做:
os.system('start notepad.exe ' + tfName)
Run Code Online (Sandbox Code Playgroud)
在末尾
我不知道这是否是一个问题,但想开始考虑它.
题:
" PHP数组索引是否区分大小写 "?
例:
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse","A"=>"Dog","B"=>"Cat","C"=>"Horse");
print_r($a);
Run Code Online (Sandbox Code Playgroud)
结果:
Array ( [a] => Dog [b] => Cat [c] => Horse [A] => Dog [B] => Cat [C] => Horse )
Run Code Online (Sandbox Code Playgroud)
我已经运行了几个例子,这似乎是正确的,只是想确保我正确看到这一点.
运行时不断告诉我:
期望一个缩进的块
但是我不希望在我的except块中没有写任何内容,我只是希望它能够捕获并吞下异常.
任何人都可以提出与Python相关的优秀播客,它可能与Python或其生态系统(如django,pylons等)有关.
有没有办法可以找出Python中字符串中有多少正则表达式匹配?例如,如果我有字符串"It actually happened when it acted out of turn."
我想知道"t a"字符串中出现了多少次.在该字符串中,"t a"出现两次.我希望我的功能告诉我它出现了两次.这可能吗?
我是Python的新手,并且对日期/时间文档感到困惑.我想计算执行计算所需的时间.
在java中,我会写:
long timeBefore = System.currentTimeMillis();
doStuff();
long timeAfter = System.currentTimeMillis();
elapsed time = timeAfter - timeBefore;
Run Code Online (Sandbox Code Playgroud)
我确信它在Python中更容易.有人可以帮忙吗?
我是一个完整的Python菜鸟.如何从文件中每行的开头删除两个字符?我正在尝试这样的事情:
#!/Python26/
import re
f = open('M:/file.txt')
lines=f.readlines()
i=0;
for line in lines:
line = line.strip()
#do something here
Run Code Online (Sandbox Code Playgroud) python ×9
arrays ×1
attributes ×1
datetime ×1
exit ×1
file-io ×1
function ×1
indentation ×1
php ×1
podcast ×1
quit ×1
regex ×1
return-value ×1
syntax ×1
try-catch ×1