Skip to main content
 首页 » 编程设计

python之如何在 Python 中将 'X' 的字符串填充到最小长度

2025年05月04日43mate10pro

最近,在我的 GCSE 计算机科学课上,我们被告知编写一个程序,将某人的名字和姓氏放在一个字符串中,然后取出名字的第一个字母和姓氏的前四个字母并打印出来但是,如果用户的姓氏长度不超过一个字符,那么它会将空格替换为字母“X”。

在考试中我们不允许访问互联网,所以我在不使用互联网的情况下开发了这个程序,但现在我想知道是否有更简单的方法来编写我制作的程序。

while True: 
    fullname = input("\nPlease type in your firstname and your surname: ") 
 
    space = fullname.index(" ") 
    length = len(fullname) 
    x = "X" 
 
    endsur = length - 1 
    initialfirst = fullname[0] 
 
    fullsurname = endsur - space 
 
    if fullsurname >= 4: 
        startsur = space + 1 
        secondsur = space + 2 
        thirdsur = space + 3 
        fourthsur = space+ 4 
 
        surname = fullname[startsur] + fullname[secondsur] + fullname[thirdsur] + fullname[fourthsur] 
 
        print(initialfirst,surname) 
 
        again = input("\nWould you like to go again? (Y/N)") 
 
        if again == "y": 
            continue 
        if again == "n": 
            print("Goodbye!") 
            quit() 
 
    if fullsurname == 3: 
        startsur = space + 1 
        secondsur = space + 2 
        thirdsur = space + 3 
 
        surname = fullname[startsur] + fullname[secondsur] + fullname[thirdsur] + x 
 
        print(initialfirst,surname) 
 
        again = input("\nWould you like to go again? (Y/N)") 
 
        if again == "y": 
            continue 
        if again == "n": 
            print("Goodbye!") 
            quit() 
 
    if fullsurname == 2: 
        startsur = space + 1 
        secondsur = space + 2 
 
        surname = fullname[startsur] + fullname[secondsur] + x + x 
 
        if again == "y": 
            continue 
        if again == "n": 
            print("Goodbye!") 
            quit() 
 
    if fullsurname == 1: 
        startsur = space + 1 
 
        surname = fullname[startsur] + x + x + x 
 
        if again == "y": 
            continue 
        if again == "n": 
            print("Goodbye!") 
            quit() 
 
    if fullsurname <= 0: 
        print("\nIt looks like you've not put in your surname. Please make sure to use a space between your firstname and your surname.") 

请您参考如下方法:

while True: 
    name = input('What is your name? ') 
    name = name.split(' ') 
    first_name = name[0] 
    last_name = name[1] 
 
    if len(last_name) < 4: 
        last_name += 'x'*(4-len(last_name)) 
 
    together = first_name[0] + last_name[0:4] 
 
    #You can add your error checks here 
    print(together) 
 
    cont = input('Would you like to go again? ') 
    if cont == 'y': 
        pass 
    else: 
        break