2018-12-19

Little Tips for Python

1.python中如何使print函数不换行

print函数

打开python shell
输入help(print),查看print函数的定义,可以发现换行符是因为 end='\n',因此将其改为 end=' ',即可

2.readlines(),readline()

try:
    with open('rea.txt','r+') as f:
        lines=f.readline()
        print(type(lines))
except:
    print('Fail.')
readline()返回数据类型
try:
    with open('rea.txt','r+') as f:
        lines=f.readlines()
        print(type(lines))
except:
    print('Fail.')
readlines()返回数据类型
## type(f.read())  --->str
## type(f.readline())  --->str
## type(f.readlines())  --->list
with open('rea.txt','r') as f:
    for line in f.readlines():
        print(line,end='')
#  <====> #  等价
with open('rea.txt','r') as f:
    line=f.readline()
    while line:
        print(line,end='')       
        #f.seek(0)     --->      读取完成之后,光标会移动到末尾。如果将光标重新定向到起始位置,会出现死循环情况     
        line=f.readline()
#  <====> #  等价
with open('rea.txt','r') as f:
    for line in f:             #在Python 2.2以后,我们可以直接对一个file对象使用for循环读每行数据
        print(line,end='')
#  <====> #  等价
with open('rea.txt','r') as f:
    for line in f.read():           
        print(line,end='')

3.json 的dumps(),loads(),dump(),load()

dumps是将dict转化成str格式,loads是将str转化成dict格式。

dump和load也是类似的功能,只是与文件操作结合起来了。


示例

结果

4.file.seek()

fileObject.seek(offset[, whence])
'''
  offset − This is the position of the read/write pointer within the file.

  whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which     
  means seek relative to the current position and 2 means seek relative to the file's end.
'''

offset是作为指针的起始位置。whence参数的意义在于这个起始位置的参照点是 开头、现在位置、结尾 中的一个。

5.str.split()

S.split(sep=None, maxsplit=-1) -> list of strings
'''
        Return a list of the words in S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are
        removed from the result.
'''

很有用的一个函数,可以得到一个list,即type(S.split()) 是list

6.判断是否字符,数字,空格

str.isalpha()
str.isdigit()
str.isspace()

7.读入文件路径

path1='C:\\Users\\15261\\Desktop\\wangj676'
path2='C:/Users/15261/Desktop/wangj676'
path3=r'C:\Users\15261\Desktop\wangj676'           #  r 用于防止字符进行转义
print(path1)
print(path2)
print(path3)
结果显示

8.f-strings

f ' { } ... '
详情查看 f-strings

你可能感兴趣的:(2018-12-19)