python基础知识测试题--01 字符串

这篇博客聚焦于Python基础知识中的字符串操作,包括ord()函数转换ASCII码、代码简洁性、while循环的运用、切片技巧、split与join方法以及栈的后进先出原理。通过实例解析和练习,旨在巩固和提升Python字符串处理能力。

python基础知识测试

在使用python过程中, 很多基础知识不用回逐渐陌生, 为了增强熟悉程度, 针对python的各个基础知识点做相应的测试, 不断总结回顾.
知识点:
字符串
列表
字典
文件读写
循环遍历

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-morse-code-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目:

1.ord(i) 把字母转成ascii码

在这里插入图片描述

解题:

class Solution(object):
    def uniqueMorseRepresentations(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        mes = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        op = []
        for word in words:
            mes_j = ""
            for i in word:
                j = ord(i)-97 # ord(i) 把字母转成ascii码
                mes_j = mes_j + mes[j]
            if mes_j not in op:
                op.append(mes_j)
        return len(op)

2.缩短代码行

在这里插入图片描述

class Solution(object):
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """
        # if len(moves)%2 != 0:
        #     return False
        # if moves.count("R") != moves.count("L"):
        #     return False
        # if moves.count("U") != moves.count("D"):
        #     return False
        # else:
        #     return True
        return  moves.count("R") == moves.count("L") and moves.count("U") == moves.count("D")

3.合理利用while

在这里插入图片描述

 class Solution(object):
    def reverseString(self, s):
        """
        :type s: List[str]
        :rtype: None Do not return anything, modify s in-place instead.
        """
        i = 0
        j = len(s) - 1
        while i < j: # 关键点在此处
            s[i], s[j] = s[j], s[i]
            i = i+1
            j = j-1
        return s

4.巧妙地使用切片

在这里插入图片描述

class Solution:
    def reverseWords(self, s: str) -> str:
        temp = s.split(' ')
        res = ''
        for each in temp:
            res += each[::-1] + ' '  # 巧妙地使用切片
        return res[:-1] #最后一个空格不要

5.拆分成列表 str.split(“拆分的因子”) 拼接字符串"拼接因子".join(list)

在这里插入图片描述

class Solution:
    def numUniqueEmails(self, emails: List[str]) -> int:
        a =[]
        for email in emails:
            email = email.split("@") #主要考察 拆分成列表 str.split("拆分的因子")   拼接字符串"拼接因子".join(list)
            email = "".join(email[0].split("+")[0].split(".")+["@",email[1]])
            if email not in a:
                a.append(email)
        return len(a)

6.利用栈的含义 后进先出

在这里插入图片描述

class Solution:
    def isValid(self, s: str) -> bool:
        stack = [] # 利用栈的含义 后进先出
        loop = {'(':')','{':'}','[':']'}
        for i in s:
            if i in loop:
                stack.append(i)
            elif stack and i == loop[stack[-1]]:
                stack.pop()
            else:
                return False
        # return True if not stack else False
        return stack == []

在这里插入图片描述

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if len(needle)==0:
            return 0
        # for i in range(len(haystack)-len(needle)+1): # 也可以自己写 暴力法
        #     j = i+len(needle)
        #     if haystack[i:j] == needle:
        #         return i
        if needle in haystack:
            # return haystack.index(needle) #可以用内置函数  python 字符串查找 返回索引值
            return haystack.find(needle)
        else:
            return -1

在这里插入图片描述

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        # s = s.rstrip().split(" ")
        # return len(s[-1])
        count = 0
        for i in range(len(s)):
            if s[i] != ' ':
                if s[i-1] ==" ":
                    count = 1
                else:
                    count +=1
        return count
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值