【python】实操——刷LeetCode

目录

TypeError: can only concatenate str (not "int") to str 

 凯撒加密

函数解析:

isalpha()

ord()

chr() 

两数之和

enumerate()


TypeError: can only concatenate str (not "int") to str 

 python报错TypeError: can only concatenate str (not "int") to str;这是一个类型转换异常,在Python中是不能向java一样,字符串拼接任何类型都变成字符串,异常分析:

扫描二维码关注公众号,回复: 15562547 查看本文章

         这个错误是因为你在Python中尝试将一个整数(int)变量和字符串(str)变量相加,而Python中的字符串只能与另一个字符串连接。例如,以下代码会导致此错误:

age = 24 
print("I am " + age + " years old.")

要解决这个问题,您可以使用以下两种方法之一:

1,将整数转换为字符串

        您可以使用str()函数将整数变量转换为字符串。例如:

age = 24 
print("I am " + str(age) + " years old.")

2,使用快速格式化字符串

age = 24 
print(f"I am {age} years old.")

总结:在Python中不同类型之间不能使用字符串拼接:比如str和num之间拼接; 

 凯撒加密

使用python语言,实现凯撒加密;

(1)将给定字符串进行加密、解密;

def caesar_cipher(text, shift):
    result = ""
    for char in text:
        if char.isalpha():
            # 将字符转换为数字(A/a 对应 0,B/b 对应 1,以此类推)
            num = ord(char.lower()) - ord('a')
            # 对数字进行位移操作
            num = (num + shift) % 26
            # 将数字转换回字符
            char = chr(num + ord('a'))
        result += char
    return result

函数解析:

isalpha()

   isalpha() 是 Python 字符串对象的一个方法,用于判断字符串是否只包含字母字符。如果字符串中只包含字母字符,则返回 True;否则返回 False

示例代码:

s1 = 'hello'
s2 = 'hello123'
s3 = '你好'

print(s1.isalpha())  # True
print(s2.isalpha())  # False
print(s3.isalpha())  # True(中文字符也被认为是字母字符)

        在上面的代码中,我们分别定义了三个字符串 s1s2s3,并使用它们的 isalpha() 方法来判断字符串是否只包含字母字符。可以看到,当字符串只包含字母字符时,isalpha() 方法返回 True;当字符串中包含非字母字符时,返回 False。需要注意的是, isalpha() 方法对于中文字符也会返回 True,因为中文字符在 Unicode 编码中本质上也是一个字符。

ord()

在 Python 中,可以使用内置函数 ord() 将英文字母转换为 ASCII 码表中对应的数字。这个函数接受一个字符作为参数,并返回其在 ASCII 码表中对应的整数值。

例如,将字母 'a' 转换为 ASCII 码表中的数字:

>>> ord('b')
98
>>> ord('c')
99

需要注意的是,ord() 函数只能对单个字符进行转换。如果传入了多个字符的字符串,它会报错:

>>> ord("hello")
TypeError: ord() expected a character, but string of length 5 found

chr() 

chr()函数的功能与上面的ord()函数功能相反,不再赘述;

两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        records = dict()
        for index,value in enumerate(nums):
            if  target - value not in records:
                records[value] = index
            else:
                return[records[target - value],index]

enumerate()

enumerate() 是 Python 的一个内置函数,用于将一个可遍历的对象(例如列表、元组、字符串等)转换为一个索引序列和对应的值序列。常用于需要同时遍历索引和对应值的场景。

enumerate() 函数的语法如下:

enumerate(iterable, start=0)

        其中,iterable 是要枚举的可迭代对象,例如列表、元组、字符串等;start 是可选参数,用于指定索引起始值,默认为 0。enumerate() 函数返回一个迭代器对象,可以使用 list() 将其转换为列表。

示例代码:

lst = ['a', 'b', 'c']

# 使用 while 循环遍历 lst 的索引和对应值
i = 0
while i < len(lst):
    print(i, lst[i])
    i += 1

# 使用 for 循环和 enumerate() 遍历 lst 的索引和对应值
for i, value in enumerate(lst):
    print(i, value)

        在上面的代码中,我们定义了一个列表 lst,并分别使用 while 循环和 for 循环 + enumerate() 来遍历该列表的索引和对应值。可以看到,通过 enumerate() 函数可以更加方便地获取列表的索引和对应值,而不需要手动维护计数器变量。

猜你喜欢

转载自blog.csdn.net/m0_64231944/article/details/130855261