Python - Methods

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python - Methods相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

Python代写,Python作业代写,代写Python,代做Python

Python开发

Python,python,python

Python 介绍

Python学习之认识python

python初识