【问题标题】:Can't concatenate string with integer [duplicate]无法将字符串与整数连接[重复]
【发布时间】:2017-05-11 09:33:25
【问题描述】:

我正在用 Python 编写一个脚本来生成蛮力单词表。我已经只能连接字符串,但是我不能在列表中每个单词的最后连接一些随机数,因为它说我不能连接 str 和 int 对象......

代码:

wList = []

words = raw_input("[+]Insert the words that you wish: ")
outputFile = raw_input("[+]Insert the path to save the file: ")

wordList = words.split(",")

for x in wordList:
    for y in wordList:
        wList.append(x + y)
        wList.append(y + x)
        wList.append(x + "-" + y)
        wList.append(y + "-" + x)
        wList.append(x + "_" + y)
        wList.append(y + "_" + x)
        wList.append(x + "@" + y)
        wList.append(y + "@" + x)


for num in wordList:
    for num2 in wordList:
        for salt in range(1,10):
            wList.append(num + num2 + int(salt))
            wList.append(num2 + num + int(salt))

【问题讨论】:

标签: python string list int concatenation


【解决方案1】:

在 Python 中,您只能将 string 与另一个 string 连接。

把最后两行改成下面这样:

wList.append(num + num2 + str(salt))
wList.append(num2 + num + str(salt))

【讨论】:

  • 有效!解决起来绝对简单,但我不喜欢 Python .. 谢谢
【解决方案2】:

在 python 中,sequence 之后的+ 运算符调用concat,在运算符之前使用sequence,在运算符之后调用任何内容。在 python 中,string 是一个sequenceconcat 函数仅适用于相同类型的两个序列,即两个字符串或两个数组。在您的代码中,您将此运算符用于stringint

您需要更改将字符串与整数连接的所有位置。这里有两种可能的方法来做到这一点。

你可以把所有的整数变成字符串。例如:

wList.append(str(x) + "-" + str(y))

或者您可以使用 % 格式。例如:

wList.append("%d-%d"%(x, y))

【讨论】:

    猜你喜欢
    • 2013-02-26
    • 2011-02-20
    • 2018-09-13
    • 2011-08-16
    • 1970-01-01
    • 2023-04-11
    • 2018-06-18
    • 1970-01-01
    相关资源
    最近更新 更多