字符串常用操作,元组tuple

字符串常用操作

1.创建:单引号,双引号,三引号
•第一种方式:
str1 = 'our company is westos'
•第二种方式:
str2 = "our company is westos"
•第三种方式:
str3 = """our company is westos"""
一个反斜线加一个单一字符可以表示一个特殊字符,通常是不可打印的字符
\n: 代表换行符    \": 代表双引号本身
\t: 代表tab符    \': 代表单引号本身
例:
In [3]: s = "westos"

In [5]: print s
westos

In [6]: a = "\"westos\""

In [7]: print a
"westos"

In [8]: b = '"westos"'

In [9]: print b
"westos"

In [10]: a = "it\'s\"westos\"sunny"

In [11]: print a
it's"westos"sunny

这里写图片描述

2.特性:
索引(s[i] ):获取特定偏移的元素
.给出一个字符串,可输出任意一个字符,如果索引为负数,
.就是相当于从后向前数

切片S[i:j]提取对应的部分作为一个序列:
•上边界并不包含在内;
•如果没有给出切片的边界,切片的下边界默认为
0,上边界为字符串的长度;
•扩展的切片S[i:j:k],其中i,j含义同上,k为递增步
长,k默认为0,j默认值为字符串长度,i默认值为1;
例:
In [13]: a = "westos"

In [14]: a[-1]
Out[14]: 's'

In [15]: a[:2]
Out[15]: 'we'

In [16]: a[::]
Out[16]: 'westos'

In [18]: a[::2]   ##隔位取值
Out[18]: 'wso'

In [19]: a[1:4:2]
Out[19]: 'et'

In [20]: a[:4:2]
Out[20]: 'ws'

连接重复操作:
In [23]: print "-="*4 + "welcom" + "-="*4
-=-=-=-=welcom-=-=-=-=

In [28]: a1='qwe'

In [29]: a2='123'

In [30]: zip(a1,a2)
Out[30]: [('q', '1'), ('w', '2'), ('e', '3')]

成员操作符:in,not in
In [25]: s
Out[25]: 'westos'

In [26]: 'w' in s
Out[26]: True

In [27]: '1' in s
Out[27]: False
3.字符串是可迭代对象,用for循环实现
In [26]: for i in range(a_len):
   ....:     print i,s[i]
   ....:     
0 w
1 e
2 s
3 t
4 o
5 s

In [27]: for index,value in enumerate(a):
   ....:     print index,value
   ....:     
0 w
1 e
2 s
3 t
4 o
5 s
4.字符串常用方法
In [4]: s ='wes'
In [5]: s.
s.capitalize  s.format      s.isupper     s.rindex      s.strip
s.center      s.index       s.join        s.rjust       s.swapcase
s.count       s.isalnum     s.ljust       s.rpartition  s.title
s.decode      s.isalpha     s.lower       s.rsplit      s.translate
s.encode      s.isdigit     s.lstrip      s.rstrip      s.upper
s.endswith    s.islower     s.partition   s.split       s.zfill
s.expandtabs  s.isspace     s.replace     s.splitlines  
s.find        s.istitle     s.rfind       s.startswith
help(s.center)    ##帮助  
(1)判断字符串由什么组成:s.isdigit() ...
(2)判断是否以什么开头,以什么结尾:s.stratswith("http://")  s.endswith(".png")
(3)去除字符串的左右的空格:s.split(), s.lstrip(), s.rstrip() (主要应用在由用户输入数据的地方)
(4)字符串对齐格式化:左对齐s.ljust(40,'^'),右对齐s.rjust(40.'^'),居中s.center(40,"^")
(5)替代:s.replace(" ","")
(6)按照指定分隔符分离字符串:(默认以空格为分隔符)
In [8]: ip = '172.24.234'
In [9]: ip.split('.')
Out[9]: ['172', '24', '234']

(7)连接指定分隔符:
In [13]: ip
Out[13]: '123 123 ewe'

In [14]: a= ip.split()

In [15]: a
Out[15]: ['123', '123', 'ewe']

In [16]: '*'.join(a)
Out[16]: '123*123*ewe'


例:
#!/usr/bin/env python
#coding:utf-8
'''
变量名是否合法判断程序:

'''

# bb = "he*llo*"
while 1:
 bb = raw_input("请输入变量名:")
 if bb[0].isalpha() or bb[0] == "_":
   for i in bb[1::1]:
       if not (i.isalnum() or i == "_"):
          print ("不合法!")
          break

   else:
       print "合法!"
       break
 else:
    print ("不合法!")

这里写图片描述
这里写图片描述

5.内置方法(BIF-built-in functioncmp,len,max,min,枚举enumrate,zip
例:
In [23]: a_len = len(a)

In [24]: print a_len
6
In [26]: for i in range(a_len):
   ....:     print i,s[i]
   ....:     
0 w
1 e
2 s
3 t
4 o
5 s

In [27]: for index,value in enumerate(a):
   ....:     print index,value
   ....:     
0 w
1 e
2 s
3 t
4 o
5 s

In [28]: a1='qwe'

In [29]: a2='123'

In [30]: zip(a1,a2)
Out[30]: [('q', '1'), ('w', '2'), ('e', '3')]

元组tuple

元组tuple

为什么需要元组?
比如:打印用户的姓名
userinfo1 = "fentiao 4 male"
userinfo[0:7]
结论:字符串中操作提取姓名/年龄/性别的方式不方便,诞生元组.

元组的定义
•- 定义空元组
tuple = ()
•- 定义单个值的元组
tuple = (fentiao,)
•- 一般的元组
tuple = (fentiao, 8, male)

元组特性
• 不能对元组的值任意更改;
• 对元组分别赋值,引申对多个变量也可通过元组方式分
别赋值

1.元组的创建(可以把元组看作一个容器,任何数据类型都可以放在这个容器里面)
(1)通过赋值方式创建元组
定义单个元组,一定要在这个元素后面加逗号
In [47]: t = (1,2j,1.2,True,(3,1))

In [48]:  print type(t)
<type 'tuple'>

In [36]: t = (1,)

In [37]: print type(t)
<type 'tuple'>

(2)通过工厂方法创建元组
InIn [45]: t = tuple()

In [46]: print type(t)
<type 'tuple'>

删除:
In [2]: a = ('hello','ipython')

In [3]: del(a)

这里写图片描述

2.元组的操作
索引:
In [49]: t =('fentiao',5,'man')

In [50]: print t[0]    ##正向索引
fentiao

In [51]: print t[-1]   ##反向索引
man

In [54]: t1 = ('fentiao',5,'man',('joy1','joy2'))

In [55]: print t1[3][1]  ##元组嵌套时元素的访问
joy2


切片:
In [52]: print t[:2]
('fentiao', 5)

In [53]: print t[::-1]   ##逆转元组元素
('man', 5, 'fentiao')

连接:
In [56]: print t + t1
('fentiao', 5, 'man', 'fentiao', 5, 'man', ('joy1', 'joy2'))

重复:
In [57]: t*3
Out[57]: ('fentiao', 5, 'man', 'fentiao', 5, 'man', 'fentiao', 5, 'man')

成员操作符:
In [60]: allow_ips = ('172.25.254.1','172.25.254.2','172.25.254.3')
In [63]: if '172.25.254.1' in allow_ips:
   ....:     print "有访问权限"
   ....: else:    
   ....:     print "无访问权限"
   ....:     
有访问权限
3.元组的循环
字符串的循环:
可迭代对象
In [59]: for i in 'hello':
   ....:     print i
   ....:     
h
e
l
l
o
元组目前接触的第三个可迭代对象
In [60]: allow_ips = ('172.25.254.1','172.25.254.2','172.25.254.3')
In [62]: for ip in allow_ips:
   ....:     print ip
   ....:     
172.25.254.1
172.25.254.2
172.25.254.3

4.端口扫描器

In [67]: ip = ('172.25.254.1','172.25.254.2','172.25.254.3')

In [68]: ports = (80,22,21)

In [69]: for i in ip: 
   ....:     for port in ports:
   ....:         print "[+] Scaning %s:%d" %(i,port)
   ....:         
[+] Scaning 172.25.254.1:80
[+] Scaning 172.25.254.1:22
[+] Scaning 172.25.254.1:21
[+] Scaning 172.25.254.2:80
[+] Scaning 172.25.254.2:22
[+] Scaning 172.25.254.2:21
[+] Scaning 172.25.254.3:80
[+] Scaning 172.25.254.3:22
[+] Scaning 172.25.254.3:21

5.元组可用的内置方法
In [70]: print cmp(('a',1,2,3,4),(1,2))
1

In [71]: print max((12,34,45))
45

In [72]: print min((12,34,45))
12

zip:
In [4]: username = ("user1","user2","user3")

In [5]: password = ("123","345","456")

In [7]: zip(username,password)
Out[7]: [('user1', '123'), ('user2', '345'), ('user3', '456')]



枚举:
In [73]: ip
Out[73]: ('172.25.254.1', '172.25.254.2', '172.25.254.3')

In [74]: for i,j in enumerate(ip):
   ....:     print i,j
   ....:     
0 172.25.254.1
1 172.25.254.2
2 172.25.254.3

枚举的使用:
#!/usr/bin/env python
#coding:utf-8

goods = (('apple',2),
         ('ipad',2000),
         ('iwatch',3000)
        )
print "商品编号\t商品名称\t商品价格"
for index,value in enumerate(goods):
    print "%2d\t\t%s\t\t%.1f" %(index,value[0],value[1])

商品编号    商品名称    商品价格
 0      apple       2.0
 1      ipad        2000.0
 2      iwatch      3000.0

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值