python基础知识

version:python 2.7

 

目录

1.repr

(1)会打印出一条易于阅读的字符串

(2)把 repr 字符串传递给内置的 eval 函数

(3)在类中编写 __repr__ 方法,用自定义的方法来提供一种可供打印的字符串

(4)``和repr()做一样的事情

2.encode 和 decode

(1)decode

(2)encode

(3)区别

(4)不同编码转换,使用unicode作为中间编码



1.repr

通过repr字符串来输出调试信息

(1)会打印出一条易于阅读的字符串

区分数值类型5与字符串类型'5'

```

>>> print 5
5
>>> print "5"
5
>>> print repr("5")
'5'
```

(2)把 repr 字符串传递给内置的 eval 函数

```

>>> print eval(repr("5"))
5
```

(3)在类中编写 __repr__ 方法,用自定义的方法来提供一种可供打印的字符串

```

class BetterClass(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return "BetterClass(%d, %d)" % (self.x, self.y)

obj = BetterClass(1, 2)
print obj

>>>

BetterClass(1, 2)

```

(4)``和repr()做一样的事情

```

>>> print `"5"`
'5'

```

2.encode 和 decode

(1)decode

将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。 

(2)encode

将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。

(3)区别

搞明白要处理的是str还是unicode, 使用对的处理方法(str.decode/unicode.encode)

流程:

1)str -> decode('the_coding_of_str') -> unicode

```

mac/linux上字符串是utf-8,windows上字符串是gb2312,下面是mac上运行结果:

>>> isinstance('中文', str)
True
>>> '中文'.decode("utf-8")
u'\u4e2d\u6587'
>>> 

```

如果是windows则是'中文'.decode("gb2312")

2)unicode -> encode('the_coding_you_want') -> str

```

>>> isinstance(u'中文', unicode)
True
>>> 
>>> u'中文'.encode("gb2312")
'\xd6\xd0\xce\xc4'
>>> 

>>> u'中文'.encode('utf-8')
'\xe4\xb8\xad\xe6\x96\x87'
```

(4)不同编码转换,使用unicode作为中间编码

#s是code_A的str

s.decode('code_A').encode('code_B')

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值