2013-12-13 43 views
2

我明白规律地使用模量,但它有多种用途吗? 举例来说,我看到这个:模数符号在这里做什么?

print "key is '%s'" %keydecrypt 
print "encrypted text is '%s'" %cipher 

我不明白字符串中的模数,然后将模旁边的变量一定做。 - >是否将值替换为字符串?

+1

它用于字符串格式。你可能想看看。 – Achrome

+0

是的。它与'C'代码中的'printf'风格格式类似。 '%s'代码表示“将'str'()'应用于参数,并将结果插入到'%s'的位置。 –

回答

2

它是一个文本占位符,在这种情况下,它会将字符串中的keydecryptcipher替换为%s。所以,如果keydecryptcipherabc,输出将是:

key is 'abc' 
encrypted text is 'abc' 

但是新string.format()功能更适合,因为它是更明确:

print "key is '{0}'" .format(keydecrypt) 
print "encrypted text is '{0}'".format(cipher) 
1

是。它用变量替代。它也可以在格式化方面做更多的事情。

此外,您不需要撇号。

你也可以通过传递一个列表来使用多个变量。即;

print "key is: %s, encrypted text is: %s" % (keydecrypt, cipher) 

除%s之外还有不同的类型,如%r;

try: 
    something 
except Exception, e: 
    print "The formatted Exception is: %r" % ex 

通常比其他方式更好地使用它;

print "This is my var: " + variable 

请记住,在Python中,一切都是一个对象。