Python数据类型:
123和’123’一样吗?
>>> 123=='123'
False
>>> type(123)
<type 'int'>
>>> type('123')
<type 'str'>
>>>
Python中的数字类型有以下5种:
1.数字:
2.字符串:’’
3.列表:[]
4.元组:()
5.字典:{}
代号依次为int() or float() or long(),’’,[],(),{}
>>> a=int()
>>> b=''
>>> c=[]
>>> d=()
>>> e={}
>>> type(a),type(b),type(c),type(d),type(e)
(<type 'int'>, <type 'str'>, <type 'list'>, <type 'tuple'>, <type 'dict'>)
>>> f=float()
>>> g=long()
>>> type(f),type(g)
(<type 'float'>, <type 'long'>)
不同数据类型(主要是数字和字符串)不能相加减!!!
>>> 123+'123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 123+123.0
246.0
>>> 123+99999999999999999999999999999
100000000000000000000000000122L
raw_input–输出的是字符串,如果需要输入数字 则需要转换数据类型
int(raw_input())
++++++++
1.数字:+
++++++++
int整型(-2147483648<x<2147483647)
float浮点型
例如:0.0,12.0,-18.8,3e+7
示例:
>>> num=0.5
>>> type(num)
<type 'float'>
>>> num=2.0
>>> type(num)
<type 'float'>
long长整型
-范围很大,几乎可以说任意大的整数均可以存储。
-为了区分普通整数和长整数,需要在整数后加L或小写l
示例:
>>> g=2147483647
>>> type(g)
<type 'int'>
>>> g=2147483648
>>> type(g)
<type 'long'>
>>> a=123
>>> type(a)
<type 'int'>
>>> a=123L
>>> type(a)
<type 'long'>
>>> a=123l
>>> type(a)
<type 'long'>
复数型(complex)
-python对复数提供内嵌支持,这是其他大部分软件所没有的。
复数举例:
3.14j,8.32e-36j
>>> num=3.14j
>>> type(num)
<type 'complex'>
>>> num1=8.32e-36j
>>> type(num1)
<type 'complex'>
+++++++++++++
2.字符串:’’ String
+++++++++++++
-使用引号定义的一组可以包含数字,字母,符号(非特殊系统符号)的集合。
Strval=‘This is a test!’
Strval=“This is a test!”
Strval=’’‘This is a test!’’’
–主要就是引号(单引号,双引号,三重引号)的应用
三重引号(docstring)通常用来制作字符串,在面向对象时详解
>>> str1='Hello World'
>>> type(str1)
<type 'str'>
>>> str2="Hello World"
>>> type(str2)
<type 'str'>
–单引号和双引号定义的字符串其实是一样的,没有区别,因为输出的值最后都是单引号
>>> str1
'Hello World'
>>> str2
'Hello World'
>>> print str1
Hello World
>>> print str2
Hello World
在单双引号混用的时候:
1.成对出现
2.内单外双或内双外单
3.如果字符串内含单引号,则外面用双引号
详细可参考本人之前在博客园发表的一篇文章
Python中的引号用法总结 - 明媚如你。 - 博客园 http://www.cnblogs.com/helloworldcc/p/7243388.html
>>> say='Let's go'
File "<stdin>", line 1
say='Let's go'
^
SyntaxError: invalid syntax
>>> say="Let's go"
>>> say
"Let's go"
>>> say="Let's "go""
File "<stdin>", line 1
say="Let's "go""
^
SyntaxError: invalid syntax
>>> say="Let's \"go\"" #用反斜杠转义成普通符号来处理
>>> print say
Let's "go"
>>> say
'Let\'s "go"'
>>> mail = 'Tom:hello i am jack'
>>> print mail
Tom:hello i am jack
>>> mail = 'Tom:\n Hello\n I am jack' #转义字符\n表示换行
>>> print mail
Tom:
Hello
I am jack
>>>
>>> mail="""Tom:
... I am jack
... goobye
... """
>>> print mail
Tom:
I am jack
goobye
----用一对三双或三单引号来定义字符串,效果还是不错滴,可以保证格式化输出
>>> mail="""Tom:
... I am jack
... Goodbye
... """
>>> mail
'Tom:\n I am jack\n Goodbye\n '
>>> print mail
Tom:
I am jack
Goodbye
转义字符介绍文章:
Python 转义字符详细介绍_python_脚本之家 http://www.jb51.net/article/108990.htm
Python转义字符 - AllenW - 博客园 http://www.cnblogs.com/allenblogs/archive/2011/04/28/2031477.html
三重引号–注释或者制造字符串
>>> mail="""Tom:
... '''格式化输出’‘’
... How is everything going?
... I miss you very much.Do you miss me,too?
... Goodbye"""
>>> print mail
Tom:
‘’'格式化输出’‘’
How is everything going?
I miss you very much.Do you miss me,too?
Goodbye
Tips:
(1)单引号中可以使用双引号,中间的会当作字符串输出
(2)双引号中可以使用单引号,中间的会当作字符串输出
(3)三单引号和三双引号中间的字符串在输出时保持原来的格式。
交互模式下的注释:
>>> #换行录好了
... for i in range(10):
... print i
...
0
1
2
3
4
5
6
7
8
9
字符串的索引和切片:
按照索引取值(索引是从0开始的,切片不取结尾的,加号可以连接2个字符串):
>>> a='abcde'
>>> a[1]
'b'
>>> a[0]
'a'
>>> a[0:2]#切片,最多可以给3个参数:起始值,结束值,步长
'ab'
>>> a[0]+a[1]
'ab'
>>> a[:4]#表示从第一个字符开始切片,0-3(切片不取索引结尾值):abcd
'abcd'
>>> a[2:4]#取的是2,3索引对应的值即2+1,3+1
'cd'
>>> a[4:]#表示从第5个(索引为4)开始取
'e'
>>> a='abcdefghijk'
>>> a[0:6:2]
'ace'
>>> a[::2]
'acegik'
>>> a[::3]
'adgj'
>>> a[-1]#负数索引是从字符串的最右边往左取的
'k'
>>> a[-4:-1]#不包含-1索引对应的值即k
'hij'
========>
倒计时(需要导入time模块中的sleep函数)
>>> a = range(10,-1,-1)
>>> a
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
插入一个知识点–占位符%s:
>>> a="There are %s birds on the tree."%(25)
>>> print a
There are 25 birds on the tree.
>>> a="There are %s birds on the tree."%(raw_input('输入一个数字: '))
输入一个数字: 200
>>> print a
There are 200 birds on the tree.
>>>
原文:
https://www.cnblogs.com/helloworldcc/p/7736961.html
正式介绍Python字符串
https://blog.csdn.net/qq_35540539/article/details/80514814
python的字符串类型
一:基本使用
1 用途: 描述性质的数据,比如人的名字,单个爱好,地址
2 定义方式
name='egon' #name=str('egon')
x=str(1)
y=str(1.1)
z=str([1,2,3])
n=str({'a':1}) #str 用来转成字符串类型,可为任意类型
print(type(x))
print(type(y))
print(type(z))
print(type(n))
3 常用操作+内置的方法
优先掌握的操作(*****):
1、按索引取值(正向取+反向取) :只能取
msg='hello world'
print(type(msg[5])) #取出的z值为空格同样为str
print(msg[-1])
msg[2]='A' #里面的信息不能改不能赋值
2、切片(顾头不顾尾,步长)
msg='hello world'
print(msg[1:5],type(msg[1:5]))
print(msg[6:-1])
print(msg[6:11]) #输出的为worl 最后一位不取
print(msg[6:])
print(msg[6::2])
了解(**)
print(msg[0:5])
print(msg[0:-1])
print(msg[6:-1:2])
print(msg[-3:-6:-2])
print(msg[0:])
print(msg[::-1]) #为空格就是默认为从头开始,负1为步长为取得字符输出相反
msg='hello world'
print(msg[-3:-6:-1])
print(msg[6:9:-1])
3、长度len
msg='hello world'
print(len(msg)) #len为记录msg一共有11位
4、成员运算in和not in
print('SB' in 'my name is alex,alex is SB')
print('alex' in 'my name is alex,alex is SB')
print('egon' not in 'my name is alex,alex is SB') # 推荐 egon这个值是否包含的对错判断
print(not 'egon' in 'my name is alex,alex is SB')
print('n' in 'my name is alex,alec is sb')
print('n' not in 'my name is sdsd,dffis ')
5、移除空白strip
name=' e gon '
print(name.strip(' ')) #去除空格键的,左右都去除。但是字符中间的不能去除
print(name.strip())
name='****A*e*gon****'
print(name.strip('*'))
name='****egon****'
print(name.strip('*'))
print(name.lstrip('*')) #只去除左边的*
print(name.rstrip('*')) #只去除右边的*
pwd=input('>>: ').strip() #pwd='123 ' ,以防用户输错,系统崩溃
if pwd == '123':
print('login successful')
msg='cccabcdefgccccc'
'c'
print(msg.strip('c'))
print(’*-=egon &^’.strip(’-= &^’)) #依次去除所包含的符号
print(’-=egon&’.strip(’-=&’))
6、切分split
msg='egon:18:male:180:160'
l=msg.split(':') #split是去除:符号然后用列表的方式呈现
print(l)
print(l[3])
7、循环
msg=‘hello world’
for x in msg: #把msg中的字符一个一个的打印出来用for循环
print(x)
需要掌握的操作(****)
1、strip,lstrip,rstrip
2、lower,upper
name='EoN'
print(name.lower()) #把当中的大写换成小写
name='egonN'
print(name.upper()) #把小写字母换成大写字母
3、startswith,endswith
print('alex is SB'.startswith('alex')) # 判断是否为alex开头的字符
print('alex is SB'.endswith('B')) #判断是否B为结尾的字符
4、format的三种玩法
print('my name is %s my age is %s' %('egon',18))
print('my name is {name} my age is {age}'.format(age=18,name='egon')) # 可以打破位置的限制,但仍能指名道姓地为指定的参数传值
print('my name is {} my age is {}'.format('egon',18)) #按顺序赋予值
print('my name is {0} my age is {1} {1} {1} {1}'.format('egon',18)) #多次简单方便的赋予相关的值
5、split,rsplit
info='egon:18:male'
print(info.split(':')) #
print(info.split(':',1)) #['egon','18:male']把第一个冒号用逗号代替形成新的列表
print(info.rsplit(':',1)) #['egon:18','male']把最后一个冒号用逗号代替
6、join:只能将元素全为字符串的列表拼成一个大的字符串
info='egon:18:male'
l=info.split(':')#转换为列表
print(l)
new_info='-'.join(l)#把列表的逗号换成-符号代替
print(new_info)
num=['a','b','c']
print(':'.join(num)) #更换成'a:b:c'
num=[1,2,‘c’]
‘:’.join(num) #1+’:’+2+’:’+‘c’ 只有全是字符串才能由列表转换成一个大的字符串
7、replace
msg='my name is wupeiqi,wupeiqi is SB'
print(msg.replace('wupeiqi','Pig',1))#把字符串内的第一个wupeiqi改成pig,
print(msg)
8、isdigit
print('111.1'.isdigit()) #判断字符内是否为整型,False
print('1111'.isdigit()) #这个是整型,所以为Ture
AGE=73
age=input('>>: ').strip() #age='asdfasdf' 去除用户输入的空格
if age.isdigit(): #判断是否是数字
age=int(age)#转换成整型
if age > AGE:
print('too big')
elif age < AGE:
print('too small')
else:
print('you got it')
else:
print('必须输入数字啊傻叉')
其他操作(了解即可)(**)
1、find,rfind,index,rindex,count
msg='my name is alex,alex is hahaha'
print(msg.find('alex'))
print(msg.find('SB')) #找不到会返回-1
print(msg.index('alex'))
print(msg.index('SB')) # 找不到index会报错
print(msg.find('alex',0,3))
print(msg.count('alex'))
print(msg.count('alex',0,15))
2、center,ljust,rjust,zfill
print('info egon'.center(50,'-'))
print('info egon'.ljust(50,'-'))
print('info egon'.rjust(50,'-'))
print('info egon'.zfill(50))
3、expandtabs
print('a\tb\tc'.expandtabs(1))
4、captalize,swapcase,title
print('my name is egon'.capitalize())
print('my Name Is egon'.swapcase())
print('my name is egon'.title())
5、is数字系列
num1=b'4' #bytes
num2=u'4' #unicode,python3中无需加u就是unicode
num3='壹' #中文数字
num4='Ⅳ' #罗马数字
isdigit():bytes,unicode
print(num1.isdigit())
print(num2.isdigit())
print(num3.isdigit())
print(num4.isdigit())
isdecimal():unicode
print(num2.isdecimal())
print(num3.isdecimal())
print(num4.isdecimal())
isnumberic;unicode,中文,罗马
print(num2.isnumeric())
print(num3.isnumeric())
print(num4.isnumeric())
6、is其他
print('abasdf123123'.isalnum())
print('asdfasdf'.isalpha())
print('egon'.islower())
print('ABC'.isupper())
print(' '.isspace())
print('My Name Is Egon'.istitle())
二:该类型总结
1 存一个值or存多个值
只能存一个值
2 有序or无序
有序
3 可变or不可变
不可变
name='egon'
print(id(name))
name='alex'
print(id(name))