python打印unicode字符问题,Python打印Unicode字符

这利用了Windows控制台中的OEM代码页为控制字符打印一些可见字符.卡片适合cp437和cp850是chr(3)-chr(6). Python 3(3.6之前)不会打印一个黑色钻石的Unicode字符,但它是你为U 0004获得的:

>>> print('\N{BLACK DIAMOND SUIT}')

Traceback (most recent call last):

File "", line 1, in

File "C:\Python33\lib\encodings\cp437.py", line 19, in encode

return codecs.charmap_encode(input,self.errors,encoding_map)[0]

UnicodeEncodeError: 'charmap' codec can't encode character '\u2666' in position 0: character maps to

>>> print(chr(4))

因此:

#!python3

#coding: utf8

class Card:

def __init__(self,value,suit):

self.value = value

self.suit = suit # 1,2,3,4 = ♥♦♣♠

def print(self):

print("┌───────┐")

print("| {:<2} |".format(self.value))

print("| |")

print("| {} |".format(chr(self.suit+2)))

print("| |")

print("| {:>2} |".format(self.value))

print("└───────┘")

输出:

>>> x=Card('K',4)

>>> x.print()

┌───────┐

| K |

| |

| ♠ |

| |

| K |

└───────┘

>>> x=Card(10,3)

>>> x.print()

┌───────┐

| 10 |

| |

| ♣ |

| |

| 10 |

└───────┘

Python 3.6更新

Python 3.6使用Windows Unicode API来打印,所以现在不需要控制字符,可以使用新的格式字符串:

#!python3.6

#coding: utf8

class Card:

def __init__(self,value,suit):

self.value = value

self.suit = '♥♦♣♠'[suit-1] # 1,2,3,4 = ♥♦♣♠

def print(self):

print('┌───────┐')

print(f'| {self.value:<2} |')

print('| |')

print(f'| {self.suit} |')

print('| |')

print(f'| {self.value:>2} |')

print('└───────┘')

输出:

>>> x=Card('10',3)

>>> x.print()

┌───────┐

| 10 |

| |

| ♣ |

| |

| 10 |

└───────┘

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值