在打印语句中插入中间名变量的条件语句,或者,在名字和中间名变量之间去掉白色 space?

Conditional statement to insert middle name variable in the print statement, OR, strip white space between first name and middle name variables?

它要么从打印语句中删除 middleName 变量,然后在用户输入中间名的条件(条件语句)中将其插入打印语句中的 firstName 和 lastName 变量之间,要么在打印中保留 middleName 变量声明并在用户未输入中间名时去除 firstName 和 middleName 变量之间的白色 space,因为按照现在的代码,输出中的名字和姓氏之间会留下一个巨大的 space当用户没有输入中间名时。我如何编写这些条件过程的代码;想选择使用其中之一吗?我在别处搜索过代码,但无济于事。

这是我的代码:

import re

print('Political Elections Voter Eligibility\n\n')

pattern1 = "^[A-Z]|^[A-Z]+'[A-Z]|^[A-Z]+-[A-Z]"
pattern2 = "^[A-Z]|^[A-Z].|^[A-Z]+'[A-Z]|^[A-Z]+-[A-Z]"
pattern3 = "^[A-Z]|^[A-Z]+'[A-Z]|^[A-Z]+-[A-Z]|^[A-Z]+ [A-Z]|^[A-Z]+ [A-Z]."

while True:
    
    firstName = input("Enter your first name and tap or click 'Enter': ")
    
    print('\n')

    if re.search(pattern1, firstName):
        
        break

    else:
        
        print('\n')
        
        print('Invalid entry.')

while True:
    
    middleName = input("Enter your middle name or middle initial and tap or click 'Enter' (Optional): ")

    print('\n')

    if len(middleName)==0 or re.search(pattern2, middleName):

        break

    else:
        
        print('\n')

        print('Invalid entry.')

while True:
    
    lastName = input("Enter your last name and tap or click 'Enter': ")

    print('\n')

    if re.search(pattern3, lastName):
        
        break

    else:
        
        print('\n')

        print('Invalid entry.')

while True:
    
    try:
        age = int(input("Enter your age and tap or click 'Enter': "))

    except ValueError:
        
        print('\n')
        
        print('Invalid entry.')
        
        continue

    print('\n')

    if 1 <= age <= 125:
        
        if 1 <= age <= 17:
            print('%s %s %s, age %s, you are not eligible to vote in political elections.' % (firstName, middleName, lastName, age))
            
            break

        if 18 <= age <= 125:
            print('%s %s %s, age %s, you are eligible to vote in political elections.' % (firstName, middleName, lastName, age))
            
            break

    else:
        print('Invalid entry.')

我认为最简单的方法是将每个名称字符串连接成一个字符串并一次打印它们。

fullName = firstName + ' '  + middleName + (' ' if bool(middleName) else '')  + lastName
print('%s, age %s, you are not eligible to vote in political elections.' % (fullName, age))

如果 middleName 是一个空字符串,表达式 bool(middleName) 将被评估为 false。

规范的方法是 join 所有三个名称,然后使用 splitjoin 删除多个空格:

fullName = ' '.join([firstName, middleName, lastName])
printName = ' '.join(fullName.split())
print(printName)

这将处理任何前导或尾随空格,并且可以使用或不使用中间名。

也有效:

#(' ' if len(middleName)>0 else '')

    fullName = firstName + ' ' + middleName + (' ' if len(middleName)>0 else '')  + lastName
    print(f"{fullName}, age {age}, you are not eligible to vote in political elections.")