Tigerr107
Tigerr107

Reputation: 27

Trying to set a character in a string in a particular position to another character

I'd like to try and do this without using indexing.

def SSet(s, i, c):
#A copy of the string 's' with the character in position 'i'
#set to character 'c'
count = -1
for item in s:
    if count >= i:
        count += 1
    if count == i:
        item += c 
print(s)

print(SSet("Late", 3, "o"))

in this example, Late should be changed to Lato.

Thank you.

Upvotes: 1

Views: 56

Answers (2)

Poonam
Poonam

Reputation: 679

def SSet(s, i, c):
#A copy of the string 's' with the character in position 'i'
#set to character 'c'
    count = 0
    strNew=""
    for item in s:
        if count == i:
            strNew=strNew+c
        else:
            strNew=strNew+item
        count=count+1

    return strNew

print(SSet("Late", 3, "o"))

Upvotes: 1

Dan D.
Dan D.

Reputation: 74645

You didn't have an accumulator to hold the output and the logic on the counter was off. The following loops over the string and concatenates the character to the output unless the characters index is the index given at which point it uses the given character.

def SSet(s, i, c):
    """A copy of the string 's' with the character in position 'i' set to character 'c'"""
    res = ""
    count = -1
    for item in s:
        count += 1
        if count == i:
            res += c
        else:
            res += item
    return res

print(SSet("Late", 3, "o"))

prints

Lato

This can be written better with enumerate which removes the counter:

def SSet(s, i, c):
    """A copy of the string 's' with the character in position 'i' set to character 'c'"""
    res = ""
    for index, item in enumerate(s):
        if index == i:
            res += c
        else:
            res += item
    return res

It could also be made faster by appending the characters to a list and then joining them at the end:

def SSet(s, i, c):
    """A copy of the string 's' with the character in position 'i' set to character 'c'"""
    res = []
    for index, item in enumerate(s):
        if index == i:
            res.append(c)
        else:
            res.append(item)
    return ''.join(res)

It is also unasked for but here is how to do it with slices:

def SSet(s, i, c):
    """A copy of the string 's' with the character in position 'i' set to character 'c'"""
    return s[:i]+c+s[i+1:]

Upvotes: 1

Related Questions