【问题标题】:Rotating the characters in a string with a specific group/list of letter and symbols?使用特定组/字母和符号列表旋转字符串中的字符?
【发布时间】:2014-11-21 00:03:30
【问题描述】:

根据用户输入的字符串,您将如何根据一组特定的字母和符号旋转字符串。用户还将输入旋转量。例如,如果用户输入旋转 3,则用户已经输入的单个字符将在字符组/字符列表中向下旋转 3 个字符。

【问题讨论】:

标签: python string


【解决方案1】:

这是一个很酷的方法

 rotated = ''.join([mystring[i-offset] for i in range(len(mystring))])

如果偏移量太高,它可能会溢出(出现越界错误),如果相关,您必须考虑这一点

解释

我们索引到字符串并减去偏移量,利用负索引在 Python 中包装的事实(尽管只有一次,因此可能溢出)。列表推导允许我们对一行中的每个字符执行此操作,而连接函数让我们将它们重新组合成一个字符串

【讨论】:

    【解决方案2】:
    def rotate_left(string, offset):
        return string[offset:] + string[:offset]
    
    def rotate_right(string, offset):
        return string[-offset:] + string[:-offset]
    
    >>> rotate_left('hello world', 3)
    'lo worldhel'
    
    >>> rotate_right('hello world', 3)
    'rldhello wo'
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 2018-12-13
      • 2023-02-25
      • 2016-07-24
      • 2018-12-21
      • 1970-01-01
      • 2019-12-01
      • 1970-01-01
      相关资源
      最近更新 更多