python数据类型之字符串

一:☆字符串类型str()

        用途:

 姓名,性别,住址,身份证号码,等描述性数据

       定义方式:

‘单引号’,“双引号”,''' 三引号''' 内定义的一串字符串类型

#python 没有字符类型,只有字符串类型。

字符串类型,每个元素是可以单独取出来,还是字符串类型 

二:字符串优先掌握的操作:

      1、按索引取值(正向取+反向取) :只能取

msg = 'hello world'
print(msg[0], type(msg[0]))  #python 正向取
print(msg[-1])                #python反向取
#返回结果如下:
    h <class 'str'>
    d

 
#字符串可以通过索引取值,字符串不能修改,字符串是不可变类型。

         2、切片(顾头不顾尾,步长) 必须掌握 

msg = 'hello world'
print(msg[0:3]) #>=0 <3
print(msg[0:7]) #>=0 <7
print(msg[0:7:1]) #>=0 <7
print(msg[0:7:2]) #hello w   #hlow
print(msg[:])
#返回结果如下:
      hel
      hello w
      hello w
      hlow
      hello world

#从-1 倒着取 也不常用,知道可以通过这个方式可以 了解 掌握正这区
# print(msg[5:1:-1])
# print(msg[-1::-1])

     3、长度len

msg = 'hello world'
print(msg.__len__())
print(len(msg))
#返回结果:
  11
  11

#也可以通过循环来实现取出长度: for  ,但是这样比较麻烦,因为python已经给我们写好了一些方法,我们可以直接通过.(点)
来调用一堆python内置的方法.__len__()长度内置的特殊方法
#用的时候我们直接用len()函数,__len__()这个是python内部的一些方法,len()内置函数去调用这些方法.
#len() 调用方法 __len__() 


#字符串循环
msg = 'hello world'
count =1
for i in msg:
    print(i,count)
    count+=1

msg = 'hello world'
print(msg[0::1])
for i in msg:
    print(i)

#len() 常用的方式
count = 0
while   count < len(msg):
    print(msg[count])
    count+=1

   4、成员运算in和not in

   #成员运算,可以判断一个元素是否在某一个序列里面(列表,字典,元组,字符串),在的话,Ture,不在False 

   #not in  取反

    msg='hello world'

    print('llo' in msg)

   print('llo' not in msg)

  #返回结果如下是个布尔值 
  True
  False    

  5、移除空白strip

#strip 移出字符串头尾两遍指定的字符,默认是空格

password = '     egrep   '.strip()
print(password)
inp_passwd = input('>>:').strip()
print(inp_passwd)
#返回结果如下:通过是在 input() 用户输入的时候,防止用户多大一个空格
  egrep
  >>: mima
  mima

name = '   kai   '.strip()
print(name)
name = '******* egrep *****'.strip('*')
print(name)
#返回结果
  kai
  egrep

     6、切分split

 #split 方法是通过指定分隔符,进行切分,切成一个列表

#split 有两个参数 .split(self,sep,maxsplit)   #self 这个我们先不算参数,那么我们就有两个参数 seq,maxsplit

user_info = 'root:x:0:0::/root:/bin/bash'
print(user_info.split(':'))
print(user_info.split('/'))
返回结果如下:
  ['root', 'x', '0', '0', '', '/root', '/bin/bash']
  ['root:x:0:0::', 'root:', 'bin', 'bash']

#取出用户名,可以通过索引的方式进行取

user_info = 'root:x:0:0::/root:/bin/bash'
res=user_info.split(':')
print(res[0])
#返回结果如下,这样我们就取到用户名
root
#列子2:取出get 命令
cmd = 'get /root/a/b/c/d/txt'

print(cmd.split(‘ ’,1)[0])  #这里第一个‘空格’,切割的次数1次  第二参数是切割的次数
#返回结果如下:
get

          rsplit 

file_path='C:\\a\\d.txt'
print(file_path.rsplit('\\',1))
#返回结果:
d.txt

 

   

posted @ 2017-12-11 17:08  Egrep  阅读(209)  评论(0编辑  收藏  举报