Python 中 AttributeError: ‘list’ object has no attribute ‘join’ 错误

当我们在列表对象上调用 join() 方法时,会出现 Python“AttributeError: ‘list’ object has no attribute ‘join’ ”。 要解决该错误,需要在字符串分隔符上调用 join 方法并将列表作为参数传递给 join ,例如 '-'.join(['a','b'])

下面是一个产生上述错误的示例

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

# ⛔️ AttributeError: 'list' object has no attribute 'join'
my_str = my_list.join('-')

Python 中 AttributeError: 'list' object has no attribute 'join' 错误

我们试图在导致错误的列表上调用 join() 方法。

要解决该错误,需要对字符串分隔符调用 join() 方法并将列表作为参数传递给它。

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

my_str = '-'.join(my_list)

print(my_str)  # 👉️ "a-b-c"

str.join 方法将一个可迭代对象作为参数并返回一个字符串,该字符串是可迭代对象中字符串的串联。

调用该方法的字符串用作元素之间的分隔符。

如果我们不需要分隔符而只想将列表元素连接成一个字符串,请对空字符串调用 join() 方法。

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

my_str = ''.join(my_list)

print(my_str)  # 👉️ "abc"

请注意 ,如果可迭代对象中存在任何非字符串值,则 join() 方法会引发 TypeError

如果我们的列表包含数字或其他类型,请在调用 join() 之前将所有值转换为字符串。

my_list = ['a', 'b', 1, 2]


all_strings = list(map(str, my_list))

print(all_strings) # 👉️ ['a', 'b', '1', '2']

result = ''.join(all_strings)

print(result)  # 👉️ "ab12"

当我们尝试在列表而不是字符串上调用 join() 方法时,会出现“AttributeError: 'list' object has no attribute 'join'”。

要解决该错误,我们必须对字符串调用该方法并将列表作为参数传递给 join()

我们可以使用 dir() 函数查看对象具有的所有属性。

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

# 👉️ [... 'append', 'clear', 'copy', 'count', 'extend', 'index',
#  'insert', 'pop', 'remove', 'reverse', 'sort' ...]
print(dir(my_list))

如果将一个类传递给 dir() 函数,它会返回该类属性的名称列表,并递归地返回其基类的属性。

如果我们尝试访问不在此列表中的任何属性,我们将收到“AttributeError:'list' object has no attribute 'join'”错误。

由于 join() 不是列表实现的方法,所以导致错误。