Home > Back-end >  Python replace everything in between first and last character
Python replace everything in between first and last character

Time:04-15

Not sure how to do this in a python way. But I want to replace the characters in a string in-between the first and last characters

For example, "apples" would be "a****s", and "car" would be "c*r".

CodePudding user response:

This function assumes that the length of the input is at least 2, but you can use string indexing to get the first and last character, and then add the appropriate number of asterisks in between:

def replace_characters(s):
    return s[0]   '*' * (len(s) - 2)   s[-1]

print(replace_characters('apples')) # 'a****s'
print(replace_characters('car')) # 'c*r'
  • Related