python tutorial 学习笔记(四) Input and Output, 字符串的转换等

    技术2022-05-20  45

    print object value in the interpreter shell:

    expression statment print keyword print a,b,c sys.stdout.write()

    string module

    transfer objects to string

    str() function: human readble

    repr() function: can be read by the interpreter

    string formatting

    str.format() “{0} and {1}”.format("spam", "eggs")

    >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}

    >>> for name, phone in table.items():

    ... print '{0:10} ==> {1:10d}'.format(name, phone)

    ...

    Jack ==> 4098

    Dcab ==> 7678

    Sjoerd ==> 4127

    print 'This {food} is {adjective}.format( food='spam', adjective='absolutely horrible')

    old style

    print '%i != %i.' % (1,2)

    Methods of File Objects

    open( filename,mode) mode can be “r””w””a””r+”(both reading and wrting)”

    On Windows, text file and binary files are treated differently. The end-of-line characters in text files are automatically altered slightly when read or written. This behind-the-scenes modification will currupt binary data like that in JPEG or EXE files. So this kind of file need to be opened with “b” mode (binary mode).

    f.read([size]), read size of bytes, return “” at the end of the file

    f.readline(), return “” at the end of file, return “/n” while blank line.

    f.readlines([sizeint])

    for line in f: print line

    f.write(string),

    f.seek(offset,from_what), f.tell()

    f.close()


    最新回复(0)