如何找到字符串的中间插入一个词

How to find middle of string to insert a word

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

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() returns 是一个整数?

假设您正在使用 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']