如何查找字符串的中间部分以插入单词

时间:2017-04-06 21:43:22

标签: python-3.x caesar-cipher

我正在尝试编写一个caesar密码,但要比正常情况更难。实际加密是在一个文件上,然后分成行。对于每一行,我想在进行转换之前在开头,中间和结尾添加一个单词。到目前为止,我有这个,但它不起作用:

file = str(input("Enter input file:" ""))
my_file = open(file, "r")
file_contents = my_file.read()
#change all "e"s to "zw"s 
    for letter in file_contents:
        if letter == "e":
            file_contents = file_contents.replace(letter, "zw")
#add "hokie" to beginning, middle, and end of each line
    lines = file_contents.split('\n')
        def middle_message(lines, position, word_to_insert):
            lines = lines[:position] + word_to_insert + lines[position:]
            return lines
        message = "hokie" + middle_message(lines, len(lines)/2, "'hokie'") + "hokie"

我正在

TypeError: slice indices must be integers or None or have an __index__ method

我做错了什么?我认为len()返回一个int?

1 个答案:

答案 0 :(得分:1)

假设您使用的是python3

即使修复了len()不是整数,也需要更多优化。

让我们先解决这个问题:我们的例子就是:

a = 'abcdef'
>>> len(a)
6
>>> len(a) / 2
3.0 #this is your problem, dividing by 2 returns a float number

你得到的错误是因为浮点数(3.0和3.5)不能用作列表(或字符串)中的切片索引,以解决这个特殊情况:

>>> len(a) // 2
3

现在,为了优化:

此代码采用一个文件,我假设该文件由多行文本组成,因为您使用'\ n'分割行。

当你解决了切片部分时,你会得到另一个错误,告诉你不能用列表连接字符串(你应该在这一点上尝试使用我上面提出的修复代码,所以你了解会发生什么)

你的middle_message函数可以使用单个字符串,但你传递的变量是'lines',这是一个字符串列表。

测试我必须传递一个行索引:

message = "hokie" + middle_message(lines[0], len(lines[0])//2, "hokie") + "hokie"

所以如果你想使用'lines'中的所有字符串,列表推导循环可能会很有用,为你提供一个包含修改过的字符串的新列表。

newlines = ["hokie" + middle_message(lines[x], len(lines[x])//2, "hokie") + "hokie" for x in range(len(lines))]

我知道,这超过80个字符..你可以解决这个问题我确定;)

现在这是我通过测试获得的结果:

>>> file_contents
'This is going to be my test file\nfor checking some python cipher program.\ni want to see how it works.\n'

>>> lines
['This is going to bzw my tzwst filzw', 'for chzwcking somzw python ciphzwr program.', 'i want to szwzw how it works.', '']

>>> newlines
['hokieThis is going to hokiebzw my tzwst filzwhokie', 'hokiefor chzwcking somzw phokieython ciphzwr program.hokie', 'hokiei want to szwzhokiew how it works.hokie', 'hokiehokiehokie']