【问题标题】:What does the modulus symbol do here? [duplicate]模数符号在这里有什么作用? [复制]
【发布时间】:2013-12-31 18:35:51
【问题描述】:

我了解模数的使用规律,但它有多种用途吗? 例如,我看到了这个:

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

我不明白字符串中的模数以及变量旁边的模数必须做什么。 -->这是一种将值替换为字符串的方法吗?

【问题讨论】:

  • 用于字符串格式化。你可能想查一下。
  • 是的。它类似于C 代码中的printf 样式格式。 %s 代码的意思是“将str() 应用于参数,并插入结果代替%s”。

标签: python python-2.7 modulo modulus


【解决方案1】:

它是一个文本占位符,在这种情况下,它将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)

【讨论】:

    【解决方案2】:

    是的。它代入变量。它还可以在格式化方面做得更多。

    另外,你不需要撇号。

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

    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 中,一切都是对象。

    【讨论】:

      猜你喜欢
      • 2016-08-21
      • 2016-05-31
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      • 2019-07-11
      • 1970-01-01
      • 2011-04-22
      • 2011-05-19
      相关资源
      最近更新 更多