如何在Python中用'X'填充字符串到最小长度?

时间:2017-03-16 23:13:54

标签: python string python-3.x

最近,在我的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.")

5 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

这段代码是@Wright答案的补充:提示:避免使用不必要的变量来进一步压缩代码并避免命名空间泛滥

while 1:
    first_name, last_name  = input('What is your name? ').split(' ')
    if len(last_name) < 4:
        last_name += 'x'*(4-len(last_name))   
    together = first_name[0] + last_name[0:4]
    print(together)
    if input('Would you like to go again? ') != 'y':
        break

答案 2 :(得分:0)

print("Enter your firstname and your surname (ex. Christopher Brown)")

while True:
    name = input('> ').split()
    if name == ['q']:
        exit()
    elif len(name) < 2:
        print("Invalid input")
        continue

    print(name[0][0],name[1][:4 if len(name[1]) >= 4 else len(name[1])]+'X'*(4-len(name[1])))

我为你显着缩短了你的代码,我将所有输入的名称移到了一行上的一个变量然后它做了一些检查并从一行打印出来,欢迎你!

答案 3 :(得分:0)

确保姓氏有足够字符的最简单方法是首先附加'XXXX'填充。

fullname = input(…)
firstname, surname_x = (fullname + "XXXX").split()
print(firstname[0], surname_x[:4])

答案 4 :(得分:0)

您也可以使用Python string formatting

while True:
    name = input('What is your name? ')
    print('{:.1}{:x<4.4}'.format(*name.split(' ', 1)))
    if input('Would you like to go again? ') != 'y':
        break

.1.4表示要截断第一个和第二个名称,而x<4表示应使用x s填充第二个名称。

相关问题