码迷,mamicode.com
首页 > 编程语言 > 详细

Python - Methods

时间:2016-03-31 23:09:05      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

call a method using a period . struture like:

<objectName>.<methodName>(list of arguments, if any)

 

# Reversing a list

L = [1, 2, 3, 4, 5]
L.reverse()
print(L)f

[5, 4, 3, 2, 1]

 

# Some String Methods

print(piece of cake.startwith(pie))
print(red.startwith(blue))

True
False

 

 

Many Methds:

Lists

These methods do not alter the list:

list.index(X): find X in the list. eg. list[i] == X , return i ,  i is lowest. if X doesn‘t exist in the list, return ValueError

list.count(X): returns a count of how many times X appears in the list.

 

These methods alter the list:

  • list.append(X) adds X to the end of the list
  • list.insert(i, X) adds X at position i
  • list.extend(L) adds a list L of items to the end.
  • list.remove(X) removes the first occurence of X.
  • list.pop(i) deletes & returns item list[i], while list.pop() deletes & returns the last item
  • del list[i] deletes the ith item of list
  • list.reverse() reverses the list
  • list.sort() sorts the list

 

# Codeing Exercise: The Replacements
#using index and oter list methods, write a function replace(list, X, Y) which replaces all occurrences of X in list with Y. 
#e.g. if L = {3, 1, 4, 1, 5, 9} then replace (L, 1, 7) would be change the contents of to [3, 7, 4, 7, 5, 9].
def replace(list, X, Y): for i in range(0, list.count(X)): list.insert(list.index(X), Y) list.remove(X) print(list)

 

 

Stings

S in T is a bool indicating whether string S is substring of string T

S.index(T) finds the first index of S where T is sustring

 

Python - Methods

标签:

原文地址:http://www.cnblogs.com/elewei/p/5343154.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!