Python数据类型一数字和字符串


数据类型

使用交互界面可以直接赋值:

>>> a=10
>>> id(a)
9178176
>>> type(a)
<class 'int'>
>>> a
10

使用id()type() 函数可以查看变量的值在内存中的ID号和数据类型,同理,可以使用此种方式来查看字符串,列表,字典等。
通过使用' '," ",或''' '''的方式可以表示字符串类型。

>>> a='123'
>>> id(a)
140528106920736
>>> type(a)
<class 'str'>
>>> a
'123'

其中,列表和字典的值是可变的,其他类型值是不可变的(这里的可变和不可变指的是内存中映射的相同id下的值)

可变类型:在id不变的情况下,value可以变,则称为可变类型,如列表,字典
不可变类型:value一旦改变,id也改变,则称为不可变类型(id变,意味着创建了新的内存空间)

变量的定义规范:

  • 只能是字母,数字或下划线的任意组合
  • 变量的第一个字符不能是数字
  • 关键字不能声明为变量名

在python2和python3中,使用input()数据的输入
会有区别:
python2:

>>> t=input('input:')
input:123
>>> type(t)
<type 'int'>

python3:

>>> t=input('input:')
input:123
>>> type(t)
<class 'str'>

python2中输入的数据格式会自动存储为对应的格式,而python3中无论输入的是什么格式,最终都会是字符串的格式。python2中的raw_input()函数和python3中的input()函数是有相同的功能:
python2:

>>> t=raw_input(":")
:123
>>> type(t)
<type 'str'>
数据类型的转换

对于数据的转换可以使用str()函数或者int(),但是要将str类型转换为list类型,可以使用eval():

>>> t=input('input:')
input:[1,2,3]
>>> type(t)
<class 'str'>
>>> l=eval(t)
>>> l
[1, 2, 3]
>>> type(l)
<class 'list'>

eval()函数可以将字符串等内容转换为一条可以执行的命令,类似于shell中的|bash 命令。
需要注意的是,在python2中,使用input(),输入没有定义的变量名会报名称没有定义的错误,如果是字符串,需要带引号:

>>> input(':')
:x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'x' is not defined
>>> input(':')
:'X'
'X'
变量赋值

python支持链式赋值:

>>> a=b=c=d=10
>>> a,b,c,d
(10, 10, 10, 10)
>>> a
10

交换值python非常灵活:

>>> x=1
>>> y=2
>>> x,y=y,x
>>> x
2
>>> y
1
格式化输出

使用%s%d 可以表示字符串和数字,在格式化输出的时候可以带入:

 >>> print('this is python %d' %3)
this is python 3
>>> print('this is %s %d' %('python',3))
this is python 3
数字

python3在定义数字的时候会默认给出数字的类型(int或 float,complex),与python2不同的是python3中取消了长整型。

>>> a=10         # 系统自动添加了类型相当于 a=int(10)
>>> type(a)
<type 'int'>
>>> b=10.0       # 系统自动添加了类型相当于 a=float(10.0)
>>> type(b)   
<type 'float'>
>>> c=1-2j       # 复数
>>> type(c)
<type 'complex'>

数字进制转换:

>>> a=10             # 10进制数
>>> print(bin(a))
0b1010               # 转换为二进制 1010
>>> print(oct(a))
012                  # 转换为八进制 12
>>> print(hex(a))
0xa                  # 转换为十六进制 a
字符串处理

索引 定义字符串使用单引号,双引号或者三引号表示。python中没有定义字符的机制,如果取单个字符串的字符,可以使用序列的方式表示:

>>> a='abcdef'
>>> print(a)
abcdef
>>> print(a[0])
a
>>> print(a[1])
b

strip() 对于字符中多余符号的处理,可以使用strip()函数,默认是去掉空格:

>>> a=input('a:')
a:    abc
>>> a
'    abc'
>>> a.strip()
'abc'

去除多余的字符,可使用strip()函数:

>>> a=input('a:')
a:#####abc#####
>>> a.strip('#')
'abc'
>>> a=input('a:')
a:###***abc***&&&
>>> a.strip('#*&')
'abc'

当然,也可以只去除一边的字符:

>>> a.lstrip('#*&')
'abc***&&&'
>>> a.rstrip('#*&')
'###***abc'

split() 字符串切分,默认使用空格:

>>> name='root:x:0:0:root:/root:/bin/bash'
>>> print(name.split(':'))
['root', 'x', '0', '0', 'root', '/root', '/bin/bash']
>>> print(name.split(':')[5])
/root

指定切分的次数:

>>> print(name.split(':',1))
['root', 'x:0:0:root:/root:/bin/bash']
>>> print(name.split(':',1)[0])
root

多个空格合并为一个:

>>> name='welcom    to  new     home'
>>> name
'welcom    to  new     home'
>>> name.split()
['welcom', 'to', 'new', 'home']
>>> print(name.split())
['welcom', 'to', 'new', 'home']

切片 第一个数字为起始位(以0开始),第二个数字为结束位(不包含结束位),第三个数字为步长(取值间隔):

>>> name='abcdefgh'
>>> name[2]
'c'
>>> name[2:4]
'cd'
>>> name[2:6:2]
'ce'

len() 字符长度:

>>> name='abc'
>>> name.__len__()
3
>>> len(name)
3

startswith() 与 endswith() 判断是否以某个字符串开始或者结尾:

>>> a='hello world'
>>> a.startswith('he')
True
>>> a.endswith('old')
False
>>> a.endswith('rld')
True

replace() 字符替换,第一个字符表示要替换的字符,第二个表示新的字符,第三个数字表示替换的个数:

>>> a='hello world'
>>> a.replace('l','x',2)
'hexxo world'
>>> a.replace('l','x',3)
'hexxo worxd'

format() 格式化匹配,任意顺序也可格式化字符表示:

>>> '{} {} {}'.format('a','b',3)
'a b 3'
>>> '{0} {1} {0}'.format('a','b',3)
'a b a'
>>> '{name} {sex} {age}'.format(name='a',sex='b',age=3)
'a b 3'
>>> 'NAME:{name} SEX:{sex} AGE:{age}'.format(name='a',sex='b',age=3)
'NAME:a SEX:b AGE:3'
>>> 'NAME:{name} SEX:{sex} AGE:{age}'.format(age=3,name='a',sex='b')
'NAME:a SEX:b AGE:3'

isdigit() 判断输入的字符串是否是数字:

>>> num='123'
>>> num.isdigit()
True

find()和 rfind() 查找字符所在的索引位置,找不到时返回-1,rfind()表示从右向左查找:

>>> a='hello world'
>>> a.find('3')
-1
>>> a.find('o')
4
>>> a.find('o',4,8)
4
>>> a.find('o',5,8)
7
>>> a.rfind('o',4,8)
7

index()和rindex() 显示字符所在的下标索引,数字表示指定的索引范围,字符不存在会报错,rindex()表示从右向左查找:

>>> a='hello world'
>>> a.index('o')
4
>>> a.rindex('o')
7
>>> a.index('o',4,8)
4
>>> a.index('3')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

count() 统计字符的个数,数字表示索引范围:

>>> a='hello world'
>>> a.count('o')
2
>>> a.count('o',5,8)
1

join() 表示拼接字符串:

>>> name
['welcom', 'to', 'new', 'home']
>>> ' '.join(name)
'welcom to new home'
>>> ':'.join(name)
'welcom:to:new:home'
>>> name='welcom    to  new     home'
>>> name.split()
['welcom', 'to', 'new', 'home']
>>> ' '.join(name.split())
'welcom to new home'

center(),ljust(),rjust(),zfull() 字符填充:

>>> a='hello'
>>> a.center(30,'*')
'************hello*************'
>>> a.rjust(30,'*')
'*************************hello'
>>> a.ljust(30,'*')
'hello*************************'
>>> a.ljust(30)
'hello                         '
>>> a.zfill(30)
'0000000000000000000000000hello'

expandtabs() 指定tab键的空格数目:

>>> name='hello\tworld'
>>> print(name)
hello   world
>>> print(name.expandtabs(1))
hello world

字母大小写转换:

>>> name='hello world'
>>> name.upper()         # 全部大写
'HELLO WORLD'
>>> name.capitalize()     # 第一个单词首字母大写
'Hello world'
>>> name.swapcase()      # 大小写反转
'HELLO WORLD'
>>> name.title()        # 每个单词首字母大写
'Hello World'
>>> name='HELLO'     
>>> name.lower()      # 全部小写
'hello'

判断字符串的组成:

>>> name='hello'
>>> name.isalnum()    # 判断由字符串或数字组成
True
>>> name.isalpha()
True
>>> name='hello123'
>>> name.isalpha()      # 判断只有字母组成
False
>>> name.isalnum()
True
>>> name='123'
>>> name.isalnum()
True
>>> name='hello123###'
>>> name.isalnum()
False

判断是否为数字,多中不同的判断方式可以判断不同的数字类型, 在无特殊情况下,对数字的判断使用isdigit()即可:

>>> n1=b'5'     # Bytes 型数字
>>> n2=u'5'     # unicode, python3中默认使用此种类型数字
>>> n3='四'     # 中文数字
>>> n4='Ⅴ'     # 罗马数字
>>> n1.isdigit()
True
>>> n2.isdigit()
True
>>> n3.isdigit()
False
>>> n4.isdigit()
False

>>> n1.isnumeric()      # Bytes 类型无此方法
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'isnumeric'
>>> n2.isnumeric()
True
>>> n3.isnumeric()
True
>>> n4.isnumeric()
True

>>> n1.isdecimal()      # Bytes 类型无此方法
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'isdecimal'
>>> n2.isdecimal()
True
>>> n3.isdecimal()
False
>>> n4.isdecimal()
False
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,064评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,606评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,011评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,550评论 1 269
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,465评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,919评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,428评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,075评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,208评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,185评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,191评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,914评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,482评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,585评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,825评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,194评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,703评论 2 339

推荐阅读更多精彩内容