循环通过字符串

Ton*_*ony 2 python iteration modulo

我需要能够使用模运算符循环一串字符,以便每个字符都可以传递给一个函数.我知道这是一个简单的问题,但我对如何做到这一点感到非常困惑.这是我的,但它给了我错误"TypeError:不是在字符串格式化期间转换的所有参数".任何建议,将不胜感激.

key = 'abc'
def encrypt(key,string):
    c = ''
    for i in range(0,len(string)):
        t = (key)%3
        a = XOR(ord(string[i]),ord(t))
        b = chr(a)
        c = c + b
    return(c)
Run Code Online (Sandbox Code Playgroud)

mkr*_*er1 5

配料

以下是一些可以帮助您encrypt以简洁的方式编写函数的成分:

  1. 您可以直接迭代字符串的字符:

    >>> my_string = 'hello'
    >>> for c in my_string:
    ...     print(c)
    ...
    h
    e
    l
    l
    o
    
    Run Code Online (Sandbox Code Playgroud)
  2. 您可以使用标准库模块中的cycle函数循环遍历任何可迭代(例如,字符串)itertools:

    >>> from itertools import cycle
    >>> for x in cycle('abc'):
    ...     print(x)
    ...
    a
    b
    c
    a
    b
    c
    a
    # goes on infinitely, abort with Ctrl-C
    
    Run Code Online (Sandbox Code Playgroud)
  3. 您可以使用该zip函数同时迭代两个序列:

    >>> for a, b in zip('hello', 'world'):
    ...     print(a, b)
    ...
    h w
    e o
    l r
    l l
    o d
    
    Run Code Online (Sandbox Code Playgroud)

    编辑:正如kichik建议的那样,itertools.izip如果你处理非常大的输入字符串,你也可以使用哪个是有益的.

  4. 您可以xor使用^运算符计算两个数字:

    >>> 5 ^ 3
    6
    
    Run Code Online (Sandbox Code Playgroud)
  5. 您可以使用以下join函数将单个字符串序列连接到单个字符串:

    >>> ''.join(['hello', 'how', 'are', 'you'])
    'hellohowareyou'
    
    Run Code Online (Sandbox Code Playgroud)
  6. 您可以join使用所谓的生成器表达式进行提供,这类似于for循环,但是作为单个表达式:

    >>> ''.join(str(x+5) for x in range(3))
    '567'
    
    Run Code Online (Sandbox Code Playgroud)

把它们放在一起

from itertools import cycle, izip

def encrypt(key, string):
    return ''.join(chr(ord(k) ^ ord(c))
                   for k, c in izip(cycle(key), string))
Run Code Online (Sandbox Code Playgroud)