python 2.3*

  1. The python string formatting symbol %f specifies the precision after the decimal point.

    >>> num=18.7254>>>print("the price  is  %.2f"%num)
    the price  is18.73>>>
        
     
  2. Python string formatting symbols:

    What does %g mean by shorthand for %f and %e? Is it %f or %e?

    I tested this with the code:

    >>> a=100000>>>print("%g"%(a))100000>>> a=10000000>>>print("%g"%(a))1e+07>>> a=1000000>>>print("%g"%(a))1e+06
     
    
    
     
    
    
     
    

    It can be found that %g automatically selects the output format. In the case of six digits, it will be output in scientific notation. The article says that %g is the abbreviation of %f and %e, but I found that the above is not scientific notation. When the method is output, the output is an integer, so the following test is performed:

    >>> a=100000.0>>>print("%g"%(a))100000>>>print("%f"%(a))100000.000000>>>
     
    
     
    
    

    It is found that %g is still different from %f when it is not output with %e

    I did the following test again:

    >>> a=100000.1
    >>> print("%g"%(a))
    100000
    >>> a=1.0
    >>> print("%g"%(a))
    1
    >>> a=1.1
    >>> print("%g"%(a))
    1.1

    发现在 a=100000.1 的时候输出的数并没有小数点后面的 1,对此我对比了 C 语言 %g 的格式输出,猜想 python 中应该如同 C 语言一样,%g 用于打印数据时,会去掉多余的零,至多保留六位有效数字。

  3. 使用格式化符号进行进制转换

    >>> num=10
    >>> print('十六进制:%#x' % num)    #使用%x将十进制num格式化为十六进制
    十六进制:0xa
    >>> print('二进制:', bin(num))      #使用bin将十进制num格式化为二进制
    二进制: 0b1010
    >>> print('八进制:%#o' % num)      #使用%o将十进制num格式化为八进制
    八进制:0o12

    上面使用格式化符号进行进制转换中,多加入了一个#号,目的是在转换结果头部显示当前进制类型,如不需要,可将#号去除,如下

    >>> print('八进制:%o' % num)
    八进制:12
    >>> print('十六进制:%x' % num)
    十六进制:a
  4. 字符串截取字符继续补充:

    [::2] 表示的是从头到尾,步长为2。第一个冒号两侧的数字是指截取字符串的范围,第二个冒号后面是指截取的步长。

    >>> L=['a','b','c','d','e','f','g']
    >>> print(L[::2]) 
    ['a', 'c', 'e', 'g']
  5. 字符串的分割还有partition()这种方式。

    partition(sep)  --> (head,sep,tail)

    从左向右遇到分隔符把字符串分割成两部分,返回头、分割符、尾三部分的三元组。如果没有找到分割符,就返回头、尾两个空元素的三元组。

    s1 = "I'm a good sutdent."
    #以'good'为分割符,返回头、分割符、尾三部分。
    s2 = s1.partition('good')
    #没有找到分割符'abc',返回头、尾两个空元素的元组。
    s3 = s1.partition('abc')
    
    print(s1)
    print(s2)
    print(s3)

    结果如下:

    I'm a good sutdent.
    ("I'm a ", 'good', ' sutdent.') ("I'm a good sutdent.", '', '')
  6. 针对 Counter 的升级使用,示例如下:

    #必须引用如下库
    from collections import Counter
    
    #定义两个字符串变量
    Var1 = "1116122137143151617181920849510"
    Var2 = "1987262819009787718192084951"
    
    #以字典的形式,输出每个字符串中出现的字符及其数量
    print (Counter(Var1))
    print (Counter(Var2))

    输出如下:

    Counter({'1': 12, '2': 3, '6': 2, '3': 2, '7': 2, '4': 2, '5': 2, '8': 2, '9': 2, '0': 2})
    Counter({'1': 5, '9': 5, '8': 5, '7': 4, '2': 3, '0': 3, '6': 1, '4': 1, '5': 1})

    针对输出的结果,可以根据字典的定义进行其他必要的操作

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326382693&siteId=291194637