常见面试题整理---Python代码篇

1.如何反序的迭代一个序列

## 如何反序的迭代一个序列
tempList = [1,2,3,4]
tempList.reverse()
for x in tempList:
    print(x)

## 如果不是list,最通用但稍慢一点的解决方案是
tempTuple = (1,2,3,4)
for i in range(len(tempTuple)-1,-1,-1):
    print(tempTuple[i])

2.使用Python进行查询和替换一个文本字符串

#使用Python来来进行查询和替换一个文本字符串
# Python中的replace()可以用来进行字符串替换
tempStr = 'Hello Java,Hello Python,Use JavaScript'
print(tempStr.replace('Hello','Bye'))

#Python中的sub()可以用来查找并替换字符串,sub()使用正则表达式来匹配
import re
rex=r'(Hello|Use)'
print(re.sub(rex,'Bye',tempStr))

3.重新实现str.strip(),注意不能使用string.*strip()

# 重新实现str.strip(),注意不能使用string.*strip()
def rightStrip(tempStr,splitStr):
    endindex = tempStr.rfind(splitStr)
    while endindex != -1 and endindex == len(tempStr)-1:
        tempStr = tempStr[:endindex]
        endindex = tempStr.rfind(splitStr)
    return tempStr

def leftStrip(tempStr,splitStr):
    startindex = tempStr.find(splitStr)
    while startindex==0:
        tempStr=tempStr[startindex+1:]
        startindex = tempStr.find(splitStr)
    return tempStr

testStr = '   Hello Python  '
print(testStr)
print(rightStrip(testStr,' '))
print(leftStrip(testStr,' '))

4.Python 的参数传递
注意Python中string,tuple,number属于不可更改对象;list,dict属于可修改对象

a = 1
def fun(a):
    a=2
fun(a)
print(a)
# 1

a=[]
def fun(a):
    a.append(1)
fun(a)
print(a)
#[1]
  • 1
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值