Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用切片以lastname、firstname格式创建新字符串_Python - Fatal编程技术网

Python 使用切片以lastname、firstname格式创建新字符串

Python 使用切片以lastname、firstname格式创建新字符串,python,Python,我已经完成了其他部分,我只是需要帮助,当用户输入全名时,将新的_string2格式化为姓、名。没有语法,它只显示名字和姓氏。谢谢大家! def main(): full_name = input('Enter your full name: ') x = len(full_name) - 1 print("Your name backwards is: ") while(x >= 0): print(full_name[x], end="")

我已经完成了其他部分,我只是需要帮助,当用户输入全名时,将新的_string2格式化为姓、名。没有语法,它只显示名字和姓氏。谢谢大家!

def main():
    full_name = input('Enter your full name: ')
    x = len(full_name) - 1
    print("Your name backwards is: ")
    while(x >= 0):
        print(full_name[x], end="")
        x -= 1


    y = full_name.index("")
    new_string2 = full_name[x+1:] + "" + full_name[0:y]
    print("\n""Alphabetically, your name is", new_string2 )


    new_string = full_name[x+1:] + "" + full_name[0:y]
    d={"UPPER_CASE":0, "LOWER_CASE":0}
    for c in full_name:
        if c.isupper():
            d["UPPER_CASE"]+=1
        elif c.islower():
           d["LOWER_CASE"]+=1
        else:
           pass
    print ("Your name has" , d["UPPER_CASE"] , "upper case letters and " , d["LOWER_CASE"] , "lower case letters")
    incorrect_string = "You have to be vewy, vewy twicky to twap a wascally wabbit"
    correct_string = incorrect_string.replace('w', 'r')
    print (correct_string)
main()

我只是假设姓氏总是在最后一个空格之后。而且不关心语法,只是修复了代码

替换这个

y = full_name.index("")
new_string2 = full_name[x+1:] + "" + full_name[0:y]
print("\n""Alphabetically, your name is", new_string2 )
为此:

y = full_name.split(" ")
new_string2 = y[-1:][0] + ", " + " ".join(y[:-1])
print("\n""Alphabetically, your name is", new_string2)
并删除更改后断开的以下行:

new_string = full_name[x+1:] + "" + full_name[0:y]
如果您喜欢在第一个空格前使用名字作为单词,请使用以下代码:

new_string2 = " ".join(y[1:]) + ", " + y[0]

只要小心,如果用户输入的名称没有任何空格,它将被打断(索引例外)。

名字和姓氏将被空格分隔吗?给出输入和输出的例子。效果很好。非常感谢你!