Lizzy
Lizzy

Reputation: 211

rotate a string n characters to the left, except the special characters

Hi I need help rotating a string to the left n amount of times, I have done so: btw Strings is a list of strings:

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

However, i'm not sure how to do this so that in a given string, say: "The intern", the space or any special characters would not move.

s1 = "The intern"

Right now my output is: ternThe in

output I want: ern eThein

any ideas? I currently created a function that indicates when a special character and its index in a string, I used that in a for loop to know that the current character is a special character, but when it comes to rotation how would i avoid that character

Upvotes: 2

Views: 582

Answers (1)

pylang
pylang

Reputation: 44465

An intriguing question. How to rotate a string while ignoring specific characters?

Here we remove, rotate, reinsert characters.

Given

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!"

Code

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

Tests

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!"

Upvotes: 1

Related Questions