Skip to content Skip to sidebar Skip to footer

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 poin

Solution 1:

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)

Solution 2:

Theres also this :)

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

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

Solution 3:

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:])

Solution 4:

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

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

Post a Comment for "Inserting Characters In Strings In Python"