繁体   English   中英

需要帮助将字符串转换为 unicode 然后添加值

[英]need help converting string to unicode and then add values

我需要帮助将此代码转换为小写,然后子字符串删除空格,然后找到 ASCII 值,然后将它们相加得到一个总和,这就是我写的:

def main ():
    # Handshake
    print("This program computes a total value for a user's full name")

    # Prompt and read input
    fullname = input("Please enter your full name: ")

    # Convert user's full name to all lower case letters
    fullname = fullname.lower()

    # Split user's full name into substrings
    fullname = fullname.split()

    # Loop through each substring and compute
    # total ASCII value of user's name
    totalvalue = 0
    for character in fullname:
        fullname = ord(character) + totalvalue

    #Display outputs
    print("\nYour name is: ", fullname)
    print("\nThe value of your name is: ", totalvalue)

main()

两个问题:(1) 拆分后,fullname 现在是名称列表,因此您需要第二个循环来迭代字符,以及 (2) 在循环中求和时键入fullname而不是totalvalue 尝试将循环替换为:

totalvalue = 0
for name in fullname:
    for character in name:
        totalvalue += ord(character)

在使用列表推导式的情况下,这样的事情怎么样:

import sys

def main ():
    # Prompt and read input
    text= raw_input().decode(sys.stdin.encoding)
    values = [ord(c) for c in text]
    print(values)
main()

其中 values 是字符串的 ascii 值列表,您可以从那里完成其余的工作

暂无
暂无

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

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