【python】基本数据类型字符串处理

dexfire · 2020-3-10 · 次阅读


【python】基本数据类型字符串处理

1. 整型:int 关键字

整数型是最基本的数据类型,python中可以直接使用数字来定义一个数值型常量

i = 10086

数值字符串 -> 整型

# 使用int()函数直接转化str
>>> int('100')
100
#
>>> int('100h')
Traceback (most recent call last):
  File "<pyshell#87>", line 1, in <module>
    int('100h')
ValueError: invalid literal for int() with base 10: '100h'
>>> int('0x100h')
Traceback (most recent call last):
  File "<pyshell#88>", line 1, in <module>
    int('0x100h')
ValueError: invalid literal for int() with base 10: '0x100h'
>>> int('0x100')
Traceback (most recent call last):
  File "<pyshell#89>", line 1, in <module>
    int('0x100')
ValueError: invalid literal for int() with base 10: '0x100'

十六进制字符串转int

>>> int('0x100',16)
256

2. 字符型 char:chr()函数

chr(i) 返回 Unicode 码位为整数 i 的字符的字符串格式。例如,chr(97) 返回字符串 ‘a’,chr(8364) 返回字符串 ‘€’。这是 ord() 的逆函数。

实参的合法范围是 0 到 1,114,111(16 进制表示是 0x10FFFF)。如果 i 超过这个范围,会触发 ValueError 异常。

>>> chr(134)
'\x86'
>>> chr(33)
'!'
>>> for i in range(32,84):
	print(chr(i),end=' ')


  ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S

Python中是否存在char这种数据类型?

>>> type('1')
<class 'str'>

输出为 class str ,说明python语言中并没有单独定义char这种类型的。

求char类型的ASCII代码?

ord(c) 对表示单个 Unicode 字符的字符串,返回代表它 Unicode 码点的整数。例如 ord(‘a’) 返回整数 97, ord(‘€’) (欧元符号)返回 8364 。这是 chr() 的逆函数。

>>> ord('a')
97
>>> for ch in 'Hello, Python!':
	print(ord(ch),end = ' ')


72 101 108 108 111 44 32 80 121 116 104 111 110 33
>>>