Home > Blockchain >  Is there a function or a method to return the positional value of a character in a list or string in
Is there a function or a method to return the positional value of a character in a list or string in

Time:10-04

The assignment

 *Numerologists claim to be able to determine a person's character traits based on the "numeric value" of a name. The value of a name is determined by summing up the values of the letters of the name where "a" is 1, "b" is 2, "c" is 3, up to "z" being 26. For example, the name "Zelle" would have the value 26 5 12 12 5 = 60 (which happens to be a very auspicious number, by the way). Write a program that calculates the numeric value of a single name provided as input.*

Here's what I have so far

def main():
    nameString = input("Enter your name to find its numeric value: ")
    letters = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    length = len(nameString)

for i in range(length):
    pos = nameString[i]
    value = letters.find(pos)
    newValue = value   1
    print(newValue, end=" ")
    
main()

The program as it is will take the name entered, go through the loop a number of times equal to the length of the nameString. What I'm having trouble finding out is how do I get the positional value of one of the characters of the name entered. Once I have that value, I need to add 1 to it, since A in the string starts at 0, assign that to a variable, such as newValue, then loop again, and ad the value of the next letter to newValue and so on then print it out. I can't seem to find a method or function, for a string or list, that will do this for me. This chapter of the text covers strings and lists so I should use one of those to find the solution. Thanks.

CodePudding user response:

In Python, all "sequences" (including strings) have a .index() method that finds the position of a value in the sequence. For strings in participating, see: https://docs.python.org/3/library/stdtypes.html#common-sequence-operations

There is an equivalent method for lists and tuples.

CodePudding user response:

That assignement is not about position. It is about the ascii value of character. ord(chr) returns its ascii value.

name = "Zelle"
val = 0
for chr in name:
    if ord(chr) < 91
        val  = ord(chr) - 64
    else:
        val  = ord(chr) - 96

val should hold the value now

CodePudding user response:

You can consider the ord values of the string as they follow a specific pattern.

def returnWeight(x):
    return ord(x)-64 if x.isupper() else ord(x)-96

name = input()
weight = 0
for i in name:
    weight  = returnWeight(i)
print(weight)
  • Related