python常用函数(一)

本文介绍了Python中列表的基本操作,包括如何使用pop()方法移除并返回列表中的元素,replace()方法替换字符串中的部分字符,查找列表中特定值的位置,以及三种不同的列表翻转方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 列表 pop()方法

pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。

list1 = ['Google', 'Runoob', 'Taobao']
list_pop=list1.pop(1)
print "删除的项为 :", list_pop
print "列表现在为 : ", list1

以上实例输出结果如下:

删除的项为 : Runoob
列表现在为 :  ['Google', 'Taobao']

2. replace()方法
Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

  • old – 将被替换的子字符串。
  • new – 新字符串,用于替换old子字符串。
  • max – 可选字符串, 替换不超过 max 次

以下实例展示了replace()函数的使用方法:

#!/usr/bin/python
 
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);

以上实例输出结果如下:

thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string

3. 查找列表中某个值得位置
p=list.index(value)

  • list 为列表的名字
  • value为查找的值
  • p为value在list的位置

4. 翻转列表

定义一个列表,并将它翻转。

例如,对调第一个和第三个元素:

翻转前 : list = [10, 11, 12, 13, 14, 15]
翻转后 : [15, 14, 13, 12, 11, 10]

code1:

def Reverse(lst):
    return [ele for ele in reversed(lst)]
     
lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))

以上实例输出结果为:

[15, 14, 13, 12, 11, 10]

code2:

def Reverse(lst):
    lst.reverse()
    return lst
     
lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))

以上实例输出结果为:

[15, 14, 13, 12, 11, 10]

code3:

def Reverse(lst):
    new_lst = lst[::-1]
    return new_lst
     
lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))

以上实例输出结果为:

[15, 14, 13, 12, 11, 10]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值