您的位置:首页 > 编程语言 > Python开发

用Python快速开发CAM程序(4)

2014-05-23 12:38 134 查看
今天,将介绍:字符串,元组,列表,下一节将介绍函数,模块的调用,类,面向对象,与CAM程序的实际运用

一:字符串

字符串是不可变的
这意味着一旦你创造了一个字符串,你就不能再改变它了。虽然这看起来像是一件坏事,但实际上它不是。

1:按字面意义级连字符串
如果你把两个字符串按字面意义相邻放着,他们会被Python自动级连。例如,'What\'s' 'your name?'会被自动转为"What's your name?"。



2:字符串的符号

'''
使用单引号(')
你可以用单引号指示字符串,就如同'Quote me on this'这样。所有的空白,即空格和制表符都照原样保留。

使用双引号(")
在双引号中的字符串与单引号中的字符串的使用完全相同,例如"What's your name?"。
'''
#使用三引号('''或""")
'''
利用三引号,你可以指示一个多行的字符串。你可以在三引号中自由的使用单引号和双引号。例如:

This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''

3:其它运用

str1 = 'abcde'
print str1[1]
'从第1取到第4'
str2 = str1[1:4]
print str2

'字符串个数'
print len(str1)
'字符串相接'
print str1+str2
'C是否在字符串'
print 'c' in str1
'要是纯数字'
str3 = '12346'

'字符串比较,相同时返回0,不相同是1或-1'
print cmp(str1,str3)



结果如下:

b
bcd
5
abcdebcd
True
1

4:字符串的分割与替换

strx = "hi dajia"

'字符串替换'
print strx.replace('hi', 'newdd')
ss= '123123123'
print ss.replace('1', 'x')
'分割'
ip = '192.168.6.68'
print ip.split('.')



结果如下:

newdd dajia
x23x23x23
['192', '168', '6', '68']

二:元组
元组内的值是不可变的,它和字符串一样,所以如果有一个很重要的数据,并且不能修改的,就可以用元组,其它的和perl的数组一样:

实例如下:

#-*- encoding: utf-8 -*-
'''
Created on 2014年5月23日

@author: Administrator
'''

#声明元组

yz = (1,2,5,8)
print yz[0],id(yz[0]),yz[2]

#遍历元组
for tmp in range(len(yz)):
print yz[tmp]
yz[0] = 88
print yz[0],id(yz[0])

结果如下:

1 10417736 5
1
2
5
8
Traceback (most recent call last):
File "E:\Python-scripts\Python-Scripts\New_Start\All_info.py", line 14, in <module>
yz[0] = 88
TypeError: 'tuple' object does not support item assignment

从以上的结果可以看出yz[0]的值,不能改变,会报错,.之前说Python简洁,实用,高效,我觉得从以上的例子就可以看出来,我直接写程序,用面向过程去写也没有问题,不用注意什么语法

三:列表

这个列表,我放在一个主函数中,实例如下:
#-*- encoding: utf-8 -*-
'''
Created on 2014年5月23日

@author: Administrator
'''
def main():
shoplist = ['apple', 'mango', 'carrot', 'banana']
'遍历列表'
for item in shoplist:
print item

print '\nI also have to buy rice.'
'增加元素'
shoplist.append('rice')
print 'My shopping list is now', shoplist
'排序元素'
print 'I will sort my list now'
shoplist.sort()
print 'Sorted shopping list is', shoplist

print 'The first item I will buy is', shoplist[0]
olditem = shoplist[0]
'删除元素'
del shoplist[0]
print 'I bought the', olditem
print 'My shopping list is now', shoplist

if __name__ == '__main__':
main()

结果如下:

apple
mango
carrot
banana

I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: