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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With