如何将每个字符更改为字符串中的每个字符并保持原始顺序python?

时间:2018-12-06 13:43:24

标签: python file

我的代码遇到问题,我想不出一种解决方法。

注意:我不允许在我的代码中使用导入

代码如下:

def decode(in_file, out_file):
    try:
        s = ""
        chr_nums = []
        splitlst = []
        lines = []
        lst = []
        f = open('q4.txt','r')
        for line in f:
            lines = line.split()
            for i in range(len(lines)):
                b = str(lines[i])
                for l in b:
                    chr_nums = chr(ord(l) - 1)
                    for a in chr_nums:
                        c =' '.join(a)
                        print c 

                    
    except IOError:
        print "Cant decipher' {"+in_file+"} 'due to an IO Error."
        f.close()

此代码的目标是将每个单词中的每个字母替换为之前的字母。 即:将a更改为z,依此类推。

代码必须更改包含此类文本的文件:

Uif Xiffmt po uif cvt hp spvoe boe spvoe
Uif Xiffmt po uif cvt hp spvoe boe spvoe

此结果:

The Wheels on the bus go round and round
The Wheels on the bus go round and round

这是我的for循环在out_file中打印的内容:

T h e W h e e l s o n t h e b u s g o r o u n d a n d r o u n dT h e W h e e l s o n t h e b u s g o r o u n d a n d r o u n d

如何获得示例中显示的结果? 如何重新加入角色以形成原始顺序?

note2:我确实尝试过使用join,但也没有运气

note3:代码获取的文件不一定包含两次相同的句子。

2 个答案:

答案 0 :(得分:0)

使用here所述的if/else in Python's list comprehension

示例代码为

f = open('q4.txt','r')
for line in f:
    lst = list(line)
    lst2 = [chr(ord(x) - 1)  if x != ' ' else ' ' for x in lst]
    print("".join(lst2))

我得到以下输出

The Wheels on the bus go round and round    
The Wheels on the bus go round and round
[Finished in 0.1s]

答案 1 :(得分:0)

除了弗朗西斯亲王的代码外,以下是采用您的代码风格的解决方案:

def decode(foo):
    final_string = ""
    f = foo
    for line in f:
        lines = line.split()
        for i in range(len(lines)):
            b = str(lines[i])
            for l in b:
                chr_nums = chr(ord(l) - 1)
                final_string += chr_nums
            final_string += " "
        final_string += "\n" # new line
    return(final_string)

secret_text = ["Uif Xiffmt po uif cvt hp spvoe boe spvoe", 
               "Uif Xiffmt po uif cvt hp spvoe boe spvoe"]

print(decode(foo=secret_text))

请注意,完全不需要“ try”之后的前五行。它们没有影响。其余的只是在适当的时候设置空格和换行符。