学习【测试开发】---基础语法

 

https://ke.qq.com/webcourse/index.html#course_id=263945&term_id=100311278&taid=1826984598701833&vid=g14237lp7jr 

 python在初始化变量时,是不需要指定变量类型的

浮点型转换为整形时,要注意:

round()函数作用按指定的位数对数值进行四舍五入,而int()函数只做取整数部分的动作

>>> temp=78.78
>>> round(temp)
79
>>> temp=78.78
>>> round(temp,1)
78.8
>>> int(temp)
78

 

 

 

 

 

条件判断、比较相等时,两边的数据类型相同才能比较

>>> list1=['lilin',20,98]
>>> list2=('lilin',20,98)
>>> list3=['lilin',20,98]
>>> list1==list2
False
>>> list1==list3
True

 

嵌套元组转换为字典:

>>> a=(('name','zhang'),('age','17'))
>>> b=dict(a)
>>> type(b)
<class 'dict'>
>>> print(b)
{'name': 'zhang', 'age': '17'}
>>>

 

 

 

 

 

 不同进制的转换,主要用在socket编程中,如底层获取到的数据是二进制:

  

>>> bin(int('8',10))
'0b1000'
>>> oct(int('12',10))
'0o14'
>>> hex(int('25',10))
'0x19'

 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

在自动化编程中,字符串的操作比较多的,比如截取字符串,重组字符串

  upper()全部转换为大写字母   isdigit()判断是否是数字   strip()去除前后空格  

串联很简单,str1+str2 即可

快速复制字符,例如print("* " *100)

#分割字符串如下:
>>> path="d:\Program Files (x86)\Ember\ISA3 Utilities\\bin;C:\Program Files (x86)\Ember\ISA3 Utilities\bin;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;" >>> for item in path.split(";"): ... print(item) ... d:\Program Files (x86)\Ember\ISA3 Utilities\bin C:\Program Files (x86)\Ember\ISA3 Utilitiein C:\ProgramData\Oracle\Java\javapath C:\Windows\system32


>>> help(str.split)
Help on method_descriptor:


split(...)
S.split(sep=None, maxsplit=-1) -> list of strings


Return a list of the words in S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are
removed from the result.


>>> path="d:\Program Files (x86)\Ember\ISA3 Utilities\\bin;C:\Program Files (x86)\Ember\ISA3 Utilities\bin;C:\ProgramData\Oracle\J
ava\javapath;C:\Windows\system32;"
>>> print(path.split(";"))
['d:\\Program Files (x86)\\Ember\\ISA3 Utilities\\bin', 'C:\\Program Files (x86)\\Ember\\ISA3 Utilities\x08in', 'C:\\ProgramData\\
Oracle\\Java\\javapath', 'C:\\Windows\\system32', '']

 

 截取字符串,如下

>>> list1=[1,2,4,5,6]
>>> print(list1[-4:])
[2, 4, 5, 6]
>>>

替换字符串,如下

>>> temp2="I love java"
>>> print(temp2.replace("java","python"))
I love python
>>> print(temp2)
I love java

查看字符串有哪些函数,及函数的定义

>>> help(str)
Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |

#   startswith()函数,如果以指定前缀打头,则返回True.

>>> help(str.startswith)
Help on method_descriptor:

startswith(...)
S.startswith(prefix[, start[, end]]) -> bool

Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.

 

>>> help(str.find)
Help on method_descriptor:

find(...)
S.find(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.

Return -1 on failure.

#index()函数,和find()函数功能类似,但增加了错误信息(当没有找到子串时)

>>> help(str.index)
Help on method_descriptor:

index(...)
S.index(sub[, start[, end]]) -> int

Like S.find() but raise ValueError when the substring is not found.

 

#join()将迭代器中的各项串联起来,以Str为间割符 

>>> help(str.join)
Help on method_descriptor:

join(...)
S.join(iterable) -> str

Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.

 

>>> list1=['18','weeee']
>>> s=','
>>> print(s.join(list1))
18,weeee
>>> s=',,,,'
>>> print(s.join(list1))
18,,,,weeee

  

基本的列表操作

列表可以使用所有适用于序列的标准操作,如索引、分片、连接和乘法

串联也是用“+”
print(mylist+list2)
快速复制一样可用*
print(list2*2)
嵌套列表
mylist=['we','122',['yrur','3423']]
列表访问(通过索引,正向访问、逆向访问)

除了可以使用索引访问当个元素,还可以使用分片操作来访问一定范围内元素。分片操作需要两个索引来作为边界,第一个索引的元素是包含在分片内的,而第二个则不包含(这是Python的惯例)。

>>> mylist=['we','122',['yrur','3423']]
>>> print(mylist[0:2])
['we', '122']
>>> print(mylist[-3:-1])
['we', '122']

 从上面可以看到:python访问是左闭右开。

参照: http://www.cnblogs.com/IPrograming/p/Python_list_tuple.html

Python同时为提供了为序列进行分片的语法糖,如下示例:获取最后3位元素:

1 # -- coding: utf-8 --
2 numbers = [1,2,3,4,5,6,7,8,9,10]
3 
4 # 输出:[8, 9, 10]
5 print( numbers[-3:])

 

获取序列前3个元素:

1 # -- coding: utf-8 --
2 numbers = [1,2,3,4,5,6,7,8,9,10]
3 
4 # 输出:[1, 2, 3]
5 print( numbers[:3])

 等步长访问列表

在进行分片的时候开始和结束点需要进行指定(显式或隐式)。而另一个参数——步长(setp length)通常都是隐式设置的,默认值为1。

1 # -- coding: utf-8 --
2 numbers = [1,2,3,4,5,6,7,8,9,10]
3 
4 # 输出:[1, 5, 9]
5 print( numbers[::4]

 步长不能为0,但是可以为负数 —— 即从右到左提取元素。使用一个负数作为步长时,必须让开始点(开始索引)大于结束点。如下:

复制代码
 1 # -- coding: utf-8 --
 2 numbers = [1,2,3,4,5,6,7,8,9,10]
 3 
 4 # 输出:[7, 6, 5]
 5 print (numbers[6:3:-1])
 6 
 7 # 输出:[10, 8, 6, 4, 2]
 8 print (numbers[::-2])
 9 
10 # 输出:[6, 4, 2]
11 print (numbers[5::-2])
12 
13 # 输出:[10, 8]
14 print (numbers[:5:-2])
复制代码
 
-----------------------list的函数包含了:


append(...)
L.append(object) -> None -- append object to end

clear(...)
L.clear() -> None -- remove all items from L

copy(...)
L.copy() -> list -- a shallow copy of L

count(...)
L.count(value) -> integer -- return number of occurrences of value

extend(...)
L.extend(iterable) -> None -- extend list by appending elements from the iterable

index(...)
L.index(value, [start, [stop]]) -> integer -- return first index of value.

insert(...)
L.insert(index, object) -- insert object before index

pop(...)
L.pop([index]) -> item -- remove and return item at index (default l
Raises IndexError if list is empty or index is out of range.

remove(...)
L.remove(value) -> None -- remove first occurrence of value.
Raises ValueError if the value is not present.

reverse(...)  #reverse 反转
L.reverse() -- reverse *IN PLACE*

-----------------------------------------

sort(...)
L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

>>> a=[1,3,5,2,9,4,7,8,6,0]
>>> a.sort()
>>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a=[1,3,5,2,9,4,7,8,6,0]
>>> sorted(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a [1, 3, 5, 2, 9, 4, 7, 8, 6, 0]


作者:everfight
链接:https://www.jianshu.com/p/136af97abd5c
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

--------------------------------------

对于一个无序的列表a,调用a.sort(),对a进行排序后返回a。
而对于同样一个无序的列表a,调用sorted(a),对a进行排序后返回一个新的列表,而对a不产生影响。

----------------------------------------

 

 

改变列表:元素赋值

复制代码
1 # --- coding: utf-8 ---
2 x = [1,1,1]
3 
4 # 改变索引1元素的值
5 x[1] = 2
6 
7 # 输出2
8 print x[1]
复制代码

 

删除元素

复制代码
1 # -- coding: utf-8 --
2 fruits = ['apple','orange','banana']
3 
4 # 使用del语句删除元素
5 del fruits[1]
6 
7 # 输出:['apple', 'banana']
8 print fruits
复制代码

 

列表方法

更多列表的使用方法和API,请参考Python文档:http://docs.python.org/2/library/functions.html#list

append:用于在列表末尾追加新对象:

复制代码
1 # -- coding: utf-8 --
2 
3 # append函数
4 lst = [1,2,3]
5 lst.append(4)
6 # 输出:[1, 2, 3, 4]
7 print lst 
复制代码

 

count:用于统计某个元素在列表中出现的次数:

1 # count函数
2 temp_str = ['to','be','not','to','be']
3 # 输出:2
4 print temp_str.count('to') 

 

extend:可以在列表末尾一次性追加另一个序列中的多个值,和连接操作不同,extend方法是修改了被扩展的序列(调用extend方法的序列),而原始的连接操作返回的是一个全新的列表

复制代码
 1 # extend函数
 2 a = [1,2,3]
 3 b = [4,5,6]
 4 a.extend(b)
 5 #输出:[1, 2, 3, 4, 5, 6]
 6 print a 
 7 # 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]
 8 print a + [7,8,9]
 9 # 输出:[1, 2, 3, 4, 5, 6]
10 print a
复制代码

 

index:用于从列表中找出某个值第一个匹配项的索引位置

复制代码
1 # index函数
2 knights = ['we','are','the','knights','who','say','ni']
3 # 输出:4
4 print knights.index('who')
5 # 抛出异常:ValueError: 'me' is not in list
6 print knights.index('me')
复制代码

 

insert:用于将对象插入到列表中

1 # insert函数
2 numbers = [1,2,3,5,6]
3 numbers.insert(3,'four')
4 # 输出:[1, 2, 3, 'four', 5, 6]
5 print numbers

 

pop:移除列表中的一个元素(默认是最后一个),并且返回该元素的值。通过pop方法可以实现一种常见的数据结构——栈(LIFO,后进先出)。

复制代码
 1 # pop函数
 2 x = [1,2,3]
 3 x.pop()
 4 # 输出:[1, 2]
 5 print x
 6 y = x.pop(0)
 7 # 输出:[2]
 8 print x
 9 # 输出:1
10 print y
复制代码

 

remove:移除列表中某个值的第一个匹配项

复制代码
1 # remove函数
2 x = ['to','be','not','to','be']
3 x.remove('to')
4 # 输出:['be', 'not', 'to', 'be']
5 print x
6 # 移除列表没有的元素会抛出异常
7 x.remove('too')
复制代码

 

reverse:将列表中的元素反向存放

1 # reverse函数
2 x = [1,2,3]
3 x.reverse()
4 # 输出:[3, 2, 1]
5 print x

 

sort:对列表进行排序。注意:sort函数时没有返回值的(None),它作用于源序列。可以通过sorted函数来获取已排序的列表副本。

复制代码
 1 # sort函数
 2 x = [3,1,2,7,6,9,5,4,8]
 3 y = x[:]
 4 z = x
 5 y.sort()
 6 # 输出:[3, 1, 2, 7, 6, 9, 5, 4, 8]
 7 print x
 8 # 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]
 9 print y
10 # 输出:[3, 1, 2, 7, 6, 9, 5, 4, 8]
11 print z
复制代码

 

cmp(x,y):通过自定义比较函数(compare),可以实现自定义排序

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2018-02-01 09:31  幸福在今天  阅读(170)  评论(0)    收藏  举报