简体   繁体   English

Python 替换第一个和最后一个字符之间的所有内容

[英]Python replace everything in between first and last character

Not sure how to do this in a python way.不确定如何以 python 的方式执行此操作。 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".例如,“apples”将是“a****s”,而“car”将是“c*r”。

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:这个 function 假设输入的长度至少为 2,但是你可以使用字符串索引来获取第一个和最后一个字符,然后在它们之间添加适当数量的星号:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM