zoukankan      html  css  js  c++  java
  • Python文件_格式运算符

    格式运算符

    1.write 方法必须用字符串来做参数,所以如果要把其他类型的值写入文件,就得先转换成字符串才行。最简单的方法就是用 str函数:

    >>> x = 50

    >>> fout.write(str(x))

    另外一个方法就是用格式运算符,也就是百分号%。在用于整数的时候,百分号%是取余数的运算符。但当第一个运算对象是字符串的时候,百分号%就成了格式运算符了。

    第一个运算对象也就是说明格式的字符串,包含一个或者更多的格式序列,规定了第二个运算对象的输出格式。返回的结果就是格式化后的字符串了。

    例如,'%d'这个格式序列的意思就是第二个运算对象要被格式化成为一个十进制的整数:

    >>> camels = 42

    >>> '%d' % camels

    '42'

    经过格式化后,结果就是字符串'42'了,而不再是整数值42了。

    2.这种格式化序列可以放到一个字符串的任何一个位置,这样就可以在一句话里面嵌入一个值了:

    >>> 'I have spotted %d camels.' % camels

    'I have spotted 42 camels.'

    3.如果格式化序列有一个以上了,那么第二个参数就必须是一个元组了。每个格式序列对应元组当中的一个元素,次序相同。

    下面的例子中,用了'%d'来格式化输出整型值,用'%g'来格式化浮点数,'%s'就是给字符串用的了。

    >>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')

    'In 3 years I have spotted 0.1 camels.'

    这里要注意,如果字符串中格式化序列有多个,那“个数”一定要和后面的元组中的元素数量相等才行。另外格式化序列与元组中元素的类型也必须一样:

    >>> '%d %d %d' % (1, 2)

    Traceback (most recent call last):

      File "<stdin>", line 1, in <module>

    TypeError: not enough arguments for format string

    >>> '%d' % 'zhongguo'

    Traceback (most recent call last):

      File "<stdin>", line 1, in <module>

    TypeError: %d format: a number is required, not str

    第一个语句中,后面元组的元素数量缺一个(格式化序列有3个,但元组缺只有2个元素),所以报错了;

    第二个语句中,元组里面的元素类型与前面格式不匹配,要求为数字,而不是字符str,所以也报错了。

    结束。

  • 相关阅读:
    learning scala view collection
    scala
    learning scala dependency injection
    learning scala implicit class
    learning scala type alise
    learning scala PartialFunction
    learning scala Function Recursive Tail Call
    learning scala Function Composition andThen
    System.Threading.Interlocked.CompareChange使用
    System.Threading.Monitor的使用
  • 原文地址:https://www.cnblogs.com/liusingbon/p/13215686.html
Copyright © 2011-2022 走看看