Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting characters in strings in python

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)
like image 629
David Avatar asked Mar 17 '16 02:03

David


1 Answers

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)
like image 179
idjaw Avatar answered Oct 04 '22 09:10

idjaw