python - 将字符串向左旋转 n 个字符,特殊字符除外

标签 python string for-loop

嗨,我需要帮助将字符串向左旋转 n 次,我已经这样做了:btw Strings 是字符串列表:

 finaltext = ""
 for i in strings:
    first = i[0 : n] 
    second = i[n :] 
    i = second + first
    finaltext += i

但是,我不知道如何执行此操作,以便在给定的字符串中说:“实习生”,空格或任何特殊字符都不会移动。

s1 = "The intern"

现在我的输出是: tern中

我想要的输出: 埃恩·埃登

有什么想法吗?我目前创建了一个函数,指示字符串中的特殊字符及其索引,我在 for 循环中使用它来知道当前字符是特殊字符,但是当涉及到旋转时,我将如何避免该字符

最佳答案

一个有趣的问题。如何旋转字符串同时忽略特定字符?

在这里,我们删除、旋转、重新插入字符。

给定

import collections as ct


def index(s):
    """Return a reversed dict of (char, [index, ...]) pairs."""
    dd = ct.defaultdict(list)
    for i, x in enumerate(s):
        dd[x].append(i)
    return dd


s1 = "The intern"
s2 = "Hello world!"

代码

def rotate(s, n=0, ignore=""):
    """Return string of rotated items, save ignored chars."""
    s0 = s[:]

    # Remove ignored chars
    for ig in ignore:
        s = s.replace(ig, "")

    # Rotate remaining string, eqiv. to `res = s[-n:] + s[:-n]`
    tail = s[-n:]
    head = ""

    for c in s[:-n]:         
        head += c    
    res = tail + head


    # Reinsert ignored chars
    if ignore:
        res = list(res)
        lookup = index(s0)
        for ig in ignore:
            for idx in lookup[ig]:
                res.insert(idx, ig)
        res = "".join(res)
    return res

测试

assert rotate(s1, n=0, ignore="") == "The intern"
assert rotate(s1, n=1, ignore="") == "nThe inter"
assert rotate(s1, n=1, ignore=" ") == "nTh einter"
assert rotate(s1, n=3, ignore=" ") == "ern Theint"

assert rotate(s2, n=12, ignore="") == "Hello world!"
assert rotate(s2, n=1, ignore="") == "!Hello world"
assert rotate(s2, n=1, ignore="H !") == "Hdell oworl!"
assert rotate(s2, n=1, ignore="!") == "dHello worl!"

关于python - 将字符串向左旋转 n 个字符,特殊字符除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58332503/

相关文章:

python - 在 Python 2.6 中导入 win32api 错误

python - 将异常处理程序分配给类的方法

javascript - 如何在javascript中将数组转换为没有逗号和空格分隔的字符串而不连接?

swift - 调用下标 [Swift] 时没有完全匹配

python - 将压缩文件读取为 pandas DataFrame

python - 单图多条线传递一组颜色?

c - 链接列表项不会打印

C++读取字符串段错误

for-loop - 使用 for 循环搜索表(字符串名称)(在 Lua 中)