Python Revisited Day 02 (数据类型)

Python 关键字


and continue except global lambda pass while as def False
if None raise with assert del finally import nonlocal return
yield break elif for in not True calss else from
is or try


1 + True # 2

整数

0b111 # 7 0b二进制
0o111 # 73 0o 八进制
0x111 # 273 0x 十六进制
divmod(5,2) # (2,1)   返回商和余数
pow(2, 3) # 2**3 8  
pow(3, 4, 2) # (3 ** 4) % 2 1
round(3.1415926, 4) #3.142 

整数转换函数

bin(7) # '0b111'  转换为二进制表示
hex(273) # '0x111' 转换为十六进制表示
oct(73)  # '0o111' 转换为八进制表示
int('A4', 16)  #164
int('A4', 15) #154
int('A4', 36) #364
int('A4', 37) #报错
#int(s, base)  base 2-36 即字符串s按照base进制转化为十进制整数 9 + 26个字母 最多表35

整数位逻辑操作符

负数的二进制表示
Python 位操作符

1|2 # 3
0b01|0b11 #3  |位逻辑or运算  注意负数是按照其补码来比较的如-3的补码为‘011111101’
1^3 #XOR运算  位上不同取1 相同取0
1&3 # 1  AND逻辑运算
1 << 3 # 8 将1左移3位 i*(2**j)
5 >>2 #右移
~3 # -4 反转3的每一位(第一位表示正负的也给安排咯)

浮点类型

math.floor(3.6)  #3
math.ceil(3.4) #4
num = 4 / 3
float.is_integer(num) #false
float.as_integer_ratio(2.75) #(11, 4)  11/4

math模块函数与常量

import math
math.acos()
math.acosh()
math.asin()
math.atan()
math,atan2(y, x)
math.atanh()
math.ceil()
math.copysign(x, y) #将x的符号设置为y的符号
math.cos()
math.cosh()
math.degrees(r) #将浮点数r从弧度转换为度数
math.e #自然常数 e
math.exp()
math.fabs(-1) #1.0
math.factorial(5) #120 5!  阶乘
math.floor()
math.fmod(x,y) # x % y better?
math.frexp(6) #(0.75, 3)   0.75 * 2 ^(3)   规格化小数   指数
math.fsum([1, 2, 3]) # 6.0
math.hypot(x, y)   #sqrt(x^2 + y ^2)
math.isinf()  #判断是否为infinity
math.isnan()
math.ldexp(m ,e) #返回m * 2^e  math.frexp反转
math.log(x, b) #b为底 可选  默认为e
math.log10(x)
math.log1p(x)#ln(1+x)
math.modf(2.2) #(0.20000000000000018, 2.0)
math.pi
math.pow(x, y) # x^y
math.radians(d) #角度到弧度
math.sin()
math.sinh()
math.sqrt()
math,tan()
math.tanh()
math.trunc(1.333)  # 1 int()

复数

c = 2 + 3j
c.real # 2.0
c.imag #3.0
c.conjugate() #(2-3j)
complex(1.2)#(1.2+0j)
complex('1+2j') #(1+2j)

精确的十进制数字 decimal

import decimal
a = decimal.Decimal(1234)
a  #Decimal('1234')
decimal.Decimal(12.34) #Decimal('12.339999999999999857891452847979962825775146484375')
decimal.Decimal('12.34') #Decimal('12.34')

math与cmath模块不适合处理decimal.Decimals,但是math模块提供一些函数可以作为decimal.Decimal的方法使用。当math.exp(x)的x为decimal.Decimal时候,应该用x.exp()

a = decimal.Decimal('12.34')
math.exp(a)#228661.9520568098
a.exp() #Decimal('228661.9520568098295904159251')

字符串

s = 'The waxwork man'
s = s[:12] + 'wo' + s[12:]
s  #'The waxwork woman'
s[::-1]  #'namow krowxaw ehT'
s * 2 #'The waxwork womanThe waxwork woman'
  • s.capitalize() 首字符变为大写
  • s.center(width, char) 返回s中间部分的一个子字符串 长度为width 并用char填充
  • s.count(t, start, end) 返回start~end 中子字符串t出现的次数
  • s.encode(encoding, err)
  • s.endswith(x, start, end) 如果字符串以x结尾返回True
  • s.expandtabs(size) 字符串中的制表符使用8个或制定个数的空格替代
  • s.find(t, start, end) 返回t在s中最左的位置 没有返回-1
  • s.format(…) 格式化
  • s.index(t, start, end) 同find?
  • s.isalnum() 如果s非空且每个字符都是字母或者数字 返回True
  • s.isalpha() 。。。都是字母。。。
  • s.isdecimal()
  • s.isdigit()
  • s.isidentifier() 。。。有效标识符。。。
  • s.islower() 。。。至少有一个可小写的字符 并且可小写的字符均为小写。。。
  • s.isupper()
  • s.isnumeric()
  • s.isprintable() 不包括换行
  • s.issapce() 。。。空白字符。。。
  • s.istitle() 一个非空的首字母大写的字符串 返回True ’ ~23213213A’ True
  • s.join(seq) ‘1’.join(‘ABC’) ‘A1B1C’
  • s.ljust(width, char)
  • s.lower() 变为小写

str.format()

'The novel {0} was published in {1}'.format('Hard Times', 1854)
#'The novel Hard Times was published in 1854'
'The novel {} was published in {}'.format('Hard Times', 1854)
#'The novel Hard Times was published in 1854'
'{{{0}}} {1} ; -}}'.format('The amount due is $', 200)
#'{The amount due is $} 200 ; -}'      {{ -> {   }} -> }
'{who} turned {age} this year'.format(who='she', age=88)
#'she turned 88 this year'
'{who} turned {age} this year'.format(who='she', age=88, 99)
#SyntaxError: positional argument follows keyword argument
'{who} turned {age} this year'.format(who='she', age=88, name = 99)
#'she turned 88 this year'
'The {who} was {0} last week'.format(12, who='boy')
#'The boy was 12 last week'
'The {who} was {0} last week'.format(who='boy', 12)
#SyntaxError: positional argument follows keyword argument
'{who} turned {age} this year'.format(99, who='she', age=88)
#'she turned 88 this year'    位置参数要放在前面!!!
stock = ['paper', 'envelopes', 'notepads']
'We have {0[1]} and {0[2]} in stock'.format(stock)
#'We have envelopes and notepads in stock'
'We have {[1]} and {[2]} in stock'.format(stock)
#tuple index out of range
d = dict(animal = 'elephant', weight = 12000)
'The {0[animal]} weighs {0[weight]}kg'.format(d)
#'The elephant weighs 12000kg'
import math
import sys
'math.pi=={0.pi} sys.maxunicode=={1.maxunicode}'.format(math,sys)
#'math.pi==3.141592653589793 sys.maxunicode==1114111' 
#从上面的例子可以看出  {}里的元素就像是一个copy,能够把不论字典  列表亦或是变量的属性和方法拷贝,非常 神奇。
element = 'Silver' 
number = 47
'The {number} is {element}'.format(**locals())
#'The 47 is Silver' 
#locals() 返回局部变量的字典,**将其拆分   形成(*=*, *=*)的一串传入函数,有上面的例子可以看到,虽然会有冗余,但并不影响结果。类似的,
'The {animal} weights, {weight}kg'.format(**d)
#'The elephant weights, 12000kg'
'{}  {}'.format(*['Eric', 'better'])
#'Eric  better'

转换

decimal.Decimal('3.1415926')
#Decimal('3.1415926')
print(decimal.Decimal('3.1415926'))
#3.1415926

上面俩种方式,第一种被称为是表象形式,这种形式的用途是提供一个被Python解释并重新构建其表示的对象。(不是很懂。。。)
第二种是以字符串形式对decimal.Decimal进行展式,这种形式的目标是便于阅读。
我们可以重写数据类型的通常行为并强制其提供字符串形式或表象形式:

  • s 用于强制使用字符串形式
  • r 用于强制使用表象形式
  • a 用于强制使用表象形式但仅限于ASCII字符
'{0} {0!s} {0!r} {0!a}'.format(decimal.Decimal('3.14'))
#"3.14 3.14 Decimal('3.14') Decimal('3.14')"
'{0} {0!s} {0!r} {0!a}'.format('ABDCE\u308b')
#"ABDCEる ABDCEる 'ABDCEる' 'ABDCE\\u308b'"
'{0} {0!s} {0!r} {0!a}'.format('ABDCEる')
#"ABDCEる ABDCEる 'ABDCEる' 'ABDCE\\u308b'"
'{0} {0!s} {0!r} {0!a}'.format('\\\\\\')
#"\\\\\\ \\\\\\ '\\\\\\\\\\\\' '\\\\\\\\\\\\'"

格式规约

用于对输出格式精确的控制
基本语法:
: fill align sign # 0 width , .precision type
字符串格式规约,由冒号(:)引入,后面跟可选的——一个填充字符,一个对齐字符(<^>分别对应左上右对齐),之后跟随最小宽度,如果需要制定最大宽度,就在其后使用 .maxwidth

'{0}'.format(s)
#'Eric hurt the little girl!'
'{0:40}'.format(s)   #默认左对齐    minimum width 40
#'Eric hurt the little girl!               '
'{0:>40}'.format(s)   #>右对齐   
#'              Eric hurt the little girl!'
'{0:^40}'.format(s)  #^ 居中对齐
#'       Eric hurt the little girl!       '
'{0:?^40}'.format(s)  #  ^ 居中对齐     填充符    ?
#'???????Eric hurt the little girl!???????'
'{0:.<40}'.format(s)  # < 左对齐    填充符   .     注意如果没有 ‘<’ 那么就变成设定maximum width 了
#'Eric hurt the little girl!..............'
'{0:.20}'.format(s)    #maximum width 20
#'Eric hurt the little'
'{0:<<30.40}'.format(s)  #fill <     left align  minimum width 30  maximum 40
#'Eric hurt the little girl!<<<<'

在格式化规约内部包括替换字段是有可能的:

maxwidth = 20
'{0}'.format(s[:maxwidth])   #采用切片操作
#'Eric hurt the little'
'{0:.{1}}'.format(s, maxwidth)   #内部替换字段
#'Eric hurt the little'

整数格式规约以冒号开始,其后可以跟随一个可选的字符对——一个填充字符,一个对齐字符(<^> 额外有一个 = 用于符号和数字之间进行填充),之后跟随的是可选的符号字符:+ 表示必须输出符号, - 表示只输出负数符号, 空格 表示为正数输出空格,为负数输出 - 。再之后跟随的是可选的最小宽度整数值——前面可以用#引导,以便获取某种基数进制为前缀的输出,也可以以0引导,以便在对齐时用0进行填充。如果希望输出其他进制的数据,需要添加一个类型字符,type:

  • b 二进制
  • o 八进制
  • x 小写十六进制
  • X 大写十六进制
  • d 十进制
  • c 整数对应的Unicode字符
  • n 表示以场所敏感的方式输出数字

以俩种不同的方式用0填充

'{0:0=12}'.format(7654321)
#'000007654321'
'{0:0=12}'.format(-7654321)
#'-00007654321'
'{0:012}'.format(7654321)
#'000007654321'
'{0:012}'.format(-7654321)
#'-00007654321'
'{0:0>12}'.format(-7654321)
#'0000-7654321'

对齐实例

'{0:*<15}'.format(123456789)
#'123456789******'
'{0:*>15}'.format(123456789)
#'******123456789'
'{0:*^15}'.format(123456789)
#'***123456789***'
'{0:*^15}'.format(123456789)
'**-123456789***'
'{0:*15}'.format(-123456789)
#报错  所以除了0填充符外  <^>=不能省略
'[{0: }] [{1: }]'.format(12345, -12345)  #space
'[ 12345] [-12345]'
'[{0:+}] [{1:+}]'.format(12345, -12345)# +
'[+12345] [-12345]'
'[{0:-}] [{1:-}]'.format(12345, -12345)#-
'[12345] [-12345]'
'{0:b} {0:o} {0:x} {0:X}'.format(12345678)
#'101111000110000101001110 57060516 bc614e BC614E'
'{0:#b} {0:#o} {0:#x} {0:#X}'.format(12345678)
#'0b101111000110000101001110 0o57060516 0xbc614e 0XBC614E'

为整数指定最大字段宽度是不可能的,因为数字无法裁剪。
在格式规范中添加 , 则整数将使用 , 分隔

'{0:,}  {0:*>13,}'.format(2.3242424e6)
#'2,324,242.4  **2,324,242.4'

至于n 它会随场所改变 给几个例子 因为我也不咋懂

import locale
locale.setlocale(locale.LC_ALL, '')
#'Chinese (Simplified)_China.936'
x,y = (1234567890, 1234.56)
locale.setlocale(locale.LC_ALL, 'C')
#'C'
c = '{0:n} {1:n}'.format(x, y)
#'1234567890 1234.56'
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
#'en_US.UTF-8'
en = '{0:n} {1:n}'.format(x, y)
#'1,234,567,890 1,234.56'
locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
#'de_DE.UTF-8'
de = '{0:n} {1:n}'.format(x, y)
#'1.234.567.890 1.234,56'
'{0:?<+19,}'.format(98765432101)
#'+98,765,432,101????'
#   ‘{0:?<+#x19}’  #好像没法和宽度  ,  啥的一起使用啊。。。

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

'{0:*<+#19X}'.format(98765432101)
#'+0X16FEE0E525******'
#总算是找到了应该要这么弄!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
用于浮点数的格式规约与用于整数的格式规约是一样的,只是在结尾处有俩个差别。在可选的最小宽度后面,通过写一个句点,并在后面跟随一个整数,我们可以指定在小数点后跟随的数字个数。我们也可以在结尾处添加一个类型字符:e表示使用小写字母e的指数形式,E表示使用大写字母E的指数形式,f表示标准的浮点形式,g表示‘通常’的形式,还有%,会导致数字扩大100倍,格式为f且多一个%。

'[{0:12.2e}] [{0:12.2f}] [{0:12.2E}]'.format(amount)
#'[    3.14e+03] [     3141.59] [    3.14E+03]'
'[{0:*>+12.2e}] [{0:*>+12.2f}] [{0:*>+12.2E}]'.format(amount)
#'[***+3.14e+03] [****+3141.59] [***+3.14E+03]'
'[{:,.6f}]'.format(decimal.Decimal('1234567890.1234567890'))
#'[1,234,567,890.123457]'

针对复数,有俩种方式可以处理:

'{0.real:.3f}{0.imag:+.3f}j'.format(4.4342+14.2j)  #python3.0以前
#'4.434+14.200j'
'{0:,.3f}'.format(4232.43323242+1323432.3232322j) #python3.1以后 与float相当
#'4,232.433+1,323,432.323j'

实例1

import sys, unicodedata


def print_unicode_table(word):
    
    print('decimal    hex    chr    {0:^40}'.format('name'))
    print('-------    ---    ---    {0:-<40}'.format(''))
    
    code = 0
    end = sys.maxunicode
    
    while code < end:
        
        c = chr(code)
        
        name = unicodedata.name(c, '*** unknown ***')
        if word is None or word in name.lower():  #word in name.lower()  if word == None, 单独执行会报错
            print('{0:7}    {0:5X}    {0:^3c}    {1}'.format(code, name.title()))
            
        code += 1
        
        

word = None
if len(sys.argv) > 1:        
    if sys.argv[1] in ('-h', '--help'):
        print('usage:{0} [string])'.format(sys.argv[0]))
        word = 0
    else:
        word = sys.argv[1].lower()
        
if word != 0:
    print_unicode_table(word)

实例2

import cmath
import math
import sys

def get_float(msg, allow_zero):

    x = None
    while x is None:

        try:
            x = float(input(msg))
            if not allow_zero and abs(x) < sys.float_info.epsilon:
                print('zero is not allowed')
                x = None

        except ValueError as  err:
            print(err)

    return x

print('ax\N{SUPERSCRIPT TWO} + bx + c = 0')
a = get_float('enter a: ', False)
b = get_float('enter b: ', True)
c = get_float('enter c: ', True)

x1 = None
x2 = None
discriminant = (b ** 2) - (4 * a * c)
if discriminant == 0:

    x1 = -(b / (2 * a))
else:
    if discriminant > 0:
        root = math.sqrt(discriminant)
    else:
        root = cmath.sqrt(discriminant)
    x1 = (-b + root) / (2 * a)
    x2 = (-b - root) / (2 * a)


equation = ('{a}x\N{SUPERSCRIPT TWO} + {b}x + {c} = 0'
            '\N{RIGHTWARDS ARROW}x = {x1}').format(**locals())
if x2 is not None:
    equation += 'or x = {}'.format(x2)

print(equation)

实例3




def print_start():

    print('<table border=\'1\'>')

def extract_fields(line):

    fields = []
    field = ""
    quote = None

    for c in line:
        if c in "\"'":
            if quote is None:
                quote = c
            elif quote == c:
                quote = None
            else:
                field += c
            continue
        if quote is None and c == ",":
            fields.append(field)
            field = ""
        else:
            field += c

    if field:
        fields.append(field)

    return fields




def excape_html(text):

    text = text.replace("&", "&amp;")
    text = text.replace("<", "&lt;")
    text = text.replace(">", "&gt;")

    return text


def print_line(line, color, maxwidth):

    print('<tr bgcolor = \'{0}\'>'.format(color))
    fields = extract_fields(line)

    for field in fields:
        if not field:
            print('<td></td>')
        else:
            number = field.replace(',', '')
            try:
                x = float(number)
                print("<td align='right'>{0:d}</td>".format(round(x)))
            except ValueError:
                field = field.title()
                field = field.replace(' And ', ' and ')
                if len(field) <= maxwidth:
                    field = excape_html(field)
                else:
                    field = "{0} ...".format(excape_html(field[:maxwidth]))

                print('<td>{0}</td>'.format(field))
    print('</tr>')


def print_end():

    print('</table>')

def main():
    maxwidth = 100
    print_start()
    count = 0

    while True:
        try:

            line = input()
            if count == 0:
                color = 'lightgreen'
            elif count % 2:
                color = 'white'
            else:
                color = 'lightyellow'

            print_line(line, color, maxwidth)
            count += 1

        except EOFError:
            break
    print_end()


if __name__ == '__main__':

    main()

练习
1.

import sys, unicodedata
def print_unicode_table(word):
    
    print('decimal    hex    chr    {0:^40}'.format('name'))
    print('-------    ---    ---    {0:-<40}'.format(''))
    
    code = 0
    end = sys.maxunicode
    
    while code < end:
        
        c = chr(code)
        
        name = unicodedata.name(c, '*** unknown ***')
        if word is None or word in name.lower():  #word in name.lower()  if word == None, 单独执行会报错
            print('{0:7}    {0:5X}    {0:^3c}    {1}'.format(code, name.title()))
            
        code += 1
words = []
while True:
    word = input('the unicodedata you need:')
    if word == '':
        break
    else:
        try:
            word = word.lower()
            words.append(word)
        except:
            print('can not lower')

words = list(set(words))

for word in words:
    if word in ('-h', '--help'):
        print('usage: {0} [string]'.format(sys.argv[0]))
    else:
        print_unicode_table(word)
print('{0:-<40}  END  {0:->40}'.format(''))
def print_start():

    print('<table border=\'1\'>')

def extract_fields(line):

    fields = []
    field = ""
    quote = None

    for c in line:
        if c in "\"'":
            if quote is None:
                quote = c
            elif quote == c:
                quote = None
            else:
                field += c
            continue
        if quote is None and c == ",":
            fields.append(field)
            field = ""
        else:
            field += c

    if field:
        fields.append(field)

    return fields




def excape_html(text):

    text = text.replace("&", "&amp;")
    text = text.replace("<", "&lt;")
    text = text.replace(">", "&gt;")

    return text


def print_line(line, color, maxwidth, de_format):

    print('<tr bgcolor = \'{0}\'>'.format(color))
    fields = extract_fields(line)

    for field in fields:
        if not field:
            print('<td></td>')
        else:
            number = field.replace(',', '')
            try:
                x = float(number)
                print("<td align='right'>{0:{1}}</td>".format(x, de_format))
            except ValueError:
                field = field.title()
                field = field.replace(' And ', ' and ')
                if len(field) <= maxwidth:
                    field = excape_html(field)
                else:
                    field = "{0} ...".format(excape_html(field[:maxwidth]))

                print('<td>{0}</td>'.format(field))
    print('</tr>')


def print_end():

    print('</table>')
    
def process_options():
    try:
        maxwidth = input('The maxwidth, defualt:100  :')
        de_format = input('The format, defualt:\'.0f\'  :')
        maxwidth = int(maxwidth)
    except ValueError:
        maxwidth = 100
    except EOFError:
        maxwidth = 100
        de_format = '.0f'
    if len(sys.argv) > 1:
        if sys.argv[1] in ('-h', '--help'):
            print("usage:\n"
                 "csv2html.py [maxwidth=int] [format=str] <infile.csv> outfile.html\n"
                 "\n\n"
                 "maxwidth is an optional integer;if specified, it sets the maximum\n"
                 "number of characters that can be output for string fields,\n"
                 "otherwise a default of 100 characters is used.\n"
                 "\n\n"
                 "foramt is the format to use for numbers; if not specified it\n"
                 "defaults to \".of\". ")
    return maxwidth, de_format

def main():
    maxwidth, de_format = process_options()
    print_start()
    count = 0

    while True:
        try:
            line = input()
            if count == 0:
                color = 'lightgreen'
            elif count % 2:
                color = 'white'
            else:
                color = 'lightyellow'

            print_line(line, color, maxwidth, de_format)
            count += 1

        except EOFError:
            break
    print_end()


if __name__ == '__main__':

    main()

转载于:https://www.cnblogs.com/MTandHJ/p/10526784.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值