David
David

Reputation: 157

How can I check whether a string index is in-bounds?

I'm doing homework and I have all except this last problem figured out. I can't seem to figure out how to get a character not to show up if it's inserted at a larger insertion point than the string has. This is the problem I'm working on:

Write a program insert.py that simulates insert behavior on a string.

The program takes three inputs: a character to be inserted, its position, and a string into which a character is to be inserted. The program prints the new version of the string. For example, if the arguments are: -, 2, below, then the program prints be-low. If a position passed to the program is outside of the bounds of the original string (in this case <0 or >5 -nothing would append on the end of below), then print the original string, without any changes (Note: an insert value of 0 OR the length of the string will add to the start or append to the end, i.e. T, 3, can will be canT; T, 0, can will be Tcan, and T, 4, can will be can).

This is what I have done so far:

C = input("Choose your charecter to insert. ")
P = int(input("Choose your character's position. "))
S = input("Choose your string. ")
st = S[:P] + C + S[P:]

print(st)
print(C, P, S)

Upvotes: 8

Views: 54570

Answers (4)

Satvinder Kaur
Satvinder Kaur

Reputation: 1

We converted the string into a list and then change the value(update the string with inserting a character between a string).

def anystring(string, position, character):
    list2=list(string)
    list2[position]=character
    return ''.join(list2)

Upvotes: -1

Vorashil Farzaliyev
Vorashil Farzaliyev

Reputation: 445

I hope you have found the answer you are looking for already. But here I would like to suggest my version.

C = input("Choose your charecter to insert. ")
P = int(input("Choose your character's position. "))
S = input("Choose your string. ")
print(S if P>len(S) else S[:P] + C + S[P:])

Upvotes: 0

Nick Pandolfi
Nick Pandolfi

Reputation: 993

Theres also this :)

result = list(S).insert(P, C)

if result:
    print(result)
else:
    print(S)

Upvotes: 3

idjaw
idjaw

Reputation: 26578

Just keep it simple. Check to see if the position is greater than the length of the word then just print the word, else proceed with your logic:

C = input("Choose your charecter to insert. ")
P = int(input("Choose your character's position. "))
S = input("Choose your string. ")

if P > len(S):
    print(S)
else:
    st = S[:P] + C + S[P:]

    print(st)
    print(C, P, S)

Upvotes: 10

Related Questions