Python的字符串格式化有两种方式: 百分号方式、format方式

百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存。[PEP-3101]

(1)百分号格式化

%[(name)][flags][width][.precision]typecode ....
  • (name) 可选,用于选择指定的key
  • flags 可选,可供选择的值有:

    + 右对齐;正数前加正好,负数前加负号;
    - 左对齐;正数前无符号,负数前加负号;
    空格 右对齐;正数前加空格,负数前加负号;
    0 右对齐;正数前无符号,负数前加负号;用0填充空白处

  • width 可选,占有宽度
  • .precision 可选,小数点后保留的位数
  • typecode 必选

    s,获取传入对象的__str__方法的返回值,并将其格式化到指定位置
    r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置
    c,整数:将数字转换成其unicode对应的值,10进制范围为 0 <= i <= 1114111(py27则只支持0-255);字符:将字符添加到指定位置
    o,将整数转换成 八 进制表示,并将其格式化到指定位置
    x,将整数转换成十六进制表示,并将其格式化到指定位置
    d,将整数、浮点数转换成 十 进制表示,并将其格式化到指定位置
    e,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(小写e)
    E,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(大写E)
    f, 将整数、浮点数转换成浮点数表示,并将其格式化到指定位置(默认保留小数点后6位)
    F,同上
    g,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是e;)
    G,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是E;)
    %,当字符串中存在格式化标志时,需要用 %%表示一个百分号

 

注意:%s, %d, %f这3个是非常常用的,当不确定用%s or %d,最好使用%s不会出错

>>> d = {'x':32,'y':27.49325,'z':65}

>>> print('%(x)-10d %(y)0.3g' % d)
32 27.5

一些例子

tpl = "i am %s" % "tomcat"
 
tpl = "i am %s age %d" % ("tomcat", 18)
 
tpl = "i am %(name)s age %(age)d" % {"name": "tomcat", "age": 18}
 
tpl = "percent %.2f" % 99.97623
 
tpl = "i am %(pp).2f" % {"pp": 123.425556, }
 
tpl = "i am %.2f %%" % {"pp": 123.425556, }

 

(2)Format()方式:

[[fill]align][sign][#][0][width][,][.precision][type]
  • fill 【可选】空白处填充的字符
  • align 【可选】对齐方式(需配合width使用)
  • <,内容左对齐
  • >,内容右对齐(默认)
  • =,内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字
  • ^,内容居中
  • sign 【可选】有无符号数字
    • +,正号加正,负号加负;
    • -,正号不变,负号加负;
    • 空格,正号空格,负号加负;
  • # 【可选】对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示
  • , 【可选】为数字添加分隔符,如:1,000,000
  • width 【可选】格式化位所占宽度
  • .precision 【可选】小数位保留精度
  • type 【可选】格式化类型
    • 传入” 字符串类型 “的参数
      • s,格式化字符串类型数据
      • 空白,未指定类型,则默认是None,同s
    • 传入“ 整数类型 ”的参数
      • b,将10进制整数自动转换成2进制表示然后格式化
      • c,将10进制整数自动转换为其对应的unicode字符
      • d,十进制整数
      • o,将10进制整数自动转换成8进制表示然后格式化;
      • x,将10进制整数自动转换成16进制表示然后格式化(小写x)
      • X,将10进制整数自动转换成16进制表示然后格式化(大写X)
    • 传入“ 浮点型或小数类型 ”的参数
      • e, 转换为科学计数法(小写e)表示,然后格式化;
      • E, 转换为科学计数法(大写E)表示,然后格式化;
      • f , 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
      • F, 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
      • g, 自动在e和f中切换
      • G, 自动在E和F中切换
      • %,显示百分比(默认显示小数点后6位)

一些例子:

tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')
  
tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])
  
tpl = "i am {0}, age {1}, really {0}".format("seven", 18)
  
tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])
  
tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)
  
tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})
  
tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])
  
tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)
  
tpl = "i am {:s}, age {:d}".format(*["seven", 18])
  
tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)
  
tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})
 
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
 
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
 
tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)
 
tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)

更多格式化操作:https://docs.python.org/3/library/string.html

 

python文件对象

文件系统和文件:
  文件系统是OS用于明确磁盘或分区上的文件的方法和数据结构--即在磁盘上组织文件的方法
  计算机文件(或称文件、电脑档案、档案)是存储在某种长期存储设备或临时存储设备中的一段数据流,并且归属于计算机文件系统管理之下

概括来讲:
  文件是计算机中由OS管理的具有名字的存储区域
  在Linux系统上,文件被看作是字节序列

 

batyes()这个内置函数,这个方法是将字符串转换为字节类型

# utf-8 一个汉子:3个字节
# gbk一个汉子:2个字节, 1bytes = 8bit
# 字符串转换字节类型:bytes(只要转换的字符串,按照什么编码)

s = "李纳斯"
n = bytes(s,encoding="utf-8")
print(n)
n = bytes(s,encoding="gbk")
print(n)

# 字节转化成字符串
new_str = str(bytes(s,encoding="utf-8"),encoding="utf-8")
print(new_str)

 

open()内置函数用于文件操作

操作文件时,一般需要经历如下步骤:

  • 打开文件
  • 操作文件
  • 关闭文件

每次都要关闭文件很麻烦,with open('文件路径','模式') as filename: 这种方式来打开文件。

#'r'为只读,'1.txt'为文件路径
f=open('1.txt','r',encoding='utf-8')  #打开文件
data=f.read()                #操作文件
f.close()                  #关闭文件
print(data)
 
# 用with语句打开,不需要自动关闭
with open('1.txt','r',encoding='utf-8') as f:
    print(f.read())

 

一、打开文件

文件句柄 = open(file, mode='r', buffering=-1, encoding=None)

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

 "b"表示以字节的方式操作

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,当以二进制的方式的效率比较高,因为磁盘底层是以字节存储

二、操作

对于文件也是个迭代对象,所以循环遍历文件的每一行用的非常多

f = open('/etc/passwd','r')
for line in f:
    print(line)
class file(object)
    def close(self): # real signature unknown; restored from __doc__
        关闭文件
        """
        close() -> None or (perhaps) an integer.  Close the file.
         
        Sets data attribute .closed to True.  A closed file cannot be used for
        further I/O operations.  close() may be called more than once without
        error.  Some kinds of file objects (for example, opened by popen())
        may return an exit status upon closing.
        """
 
    def fileno(self): # real signature unknown; restored from __doc__
        文件描述符  
         """
        fileno() -> integer "file descriptor".
         
        This is needed for lower-level file interfaces, such os.read().
        """
        return 0    
 
    def flush(self): # real signature unknown; restored from __doc__
        刷新文件内部缓冲区
        """ flush() -> None.  Flush the internal I/O buffer. """
        pass
 
 
    def isatty(self): # real signature unknown; restored from __doc__
        判断文件是否是同意tty设备
        """ isatty() -> true or false.  True if the file is connected to a tty device. """
        return False
 
 
    def next(self): # real signature unknown; restored from __doc__
        获取下一行数据,不存在,则报错
        """ x.next() -> the next value, or raise StopIteration """
        pass
 
    def read(self, size=None): # real signature unknown; restored from __doc__
        读取指定字节数据
        """
        read([size]) -> read at most size bytes, returned as a string.
         
        If the size argument is negative or omitted, read until EOF is reached.
        Notice that when in non-blocking mode, less data than what was requested
        may be returned, even if no size parameter was given.
        """
        pass
 
    def readinto(self): # real signature unknown; restored from __doc__
        读取到缓冲区,不要用,将被遗弃
        """ readinto() -> Undocumented.  Don't use this; it may go away. """
        pass
 
    def readline(self, size=None): # real signature unknown; restored from __doc__
        仅读取一行数据
        """
        readline([size]) -> next line from the file, as a string.
         
        Retain newline.  A non-negative size argument limits the maximum
        number of bytes to return (an incomplete line may be returned then).
        Return an empty string at EOF.
        """
        pass
 
    def readlines(self, size=None): # real signature unknown; restored from __doc__
        读取所有数据,并根据换行保存值列表
        """
        readlines([size]) -> list of strings, each a line from the file.
         
        Call readline() repeatedly and return a list of the lines so read.
        The optional size argument, if given, is an approximate bound on the
        total number of bytes in the lines returned.
        """
        return []
 
    def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
        指定文件中指针位置
        """
        seek(offset[, whence]) -> None.  Move to new file position.
         
        Argument offset is a byte count.  Optional argument whence defaults to
(offset from start of file, offset should be >= 0); other values are 1
        (move relative to current position, positive or negative), and 2 (move
        relative to end of file, usually negative, although many platforms allow
        seeking beyond the end of a file).  If the file is opened in text mode,
        only offsets returned by tell() are legal.  Use of other offsets causes
        undefined behavior.
        Note that not all file objects are seekable.
        """
        pass
 
    def tell(self): # real signature unknown; restored from __doc__
        获取当前指针位置
        """ tell() -> current file position, an integer (may be a long integer). """
        pass
 
    def truncate(self, size=None): # real signature unknown; restored from __doc__
        截断数据,仅保留指定之前数据
        """
        truncate([size]) -> None.  Truncate the file to at most size bytes.
         
        Size defaults to the current file position, as returned by tell().
        """
        pass
 
    def write(self, p_str): # real signature unknown; restored from __doc__
        写内容
        """
        write(str) -> None.  Write string str to file.
         
        Note that due to buffering, flush() or close() may be needed before
        the file on disk reflects the data written.
        """
        pass
 
    def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
        将一个字符串列表写入文件
        """
        writelines(sequence_of_strings) -> None.  Write the strings to the file.
         
        Note that newlines are not added.  The sequence can be any iterable object
        producing strings. This is equivalent to calling write() for each string.
        """
        pass
 
    def xreadlines(self): # real signature unknown; restored from __doc__
        可用于逐行读取文件,非全部
        """
        xreadlines() -> returns self.
         
        For backward compatibility. File objects now include the performance
        optimizations previously implemented in the xreadlines module.
        """
        pass

2.x
2.x

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-27
  • 2022-01-11
  • 2021-10-03
  • 2021-11-02
  • 2021-12-28
猜你喜欢
  • 2021-11-18
  • 2022-01-24
  • 2022-02-19
  • 2021-04-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案