How to print something when a user gives a word? - python

My question can be understood below:
goodvalue=False
while (goodvalue==False):
try:
word=str(input("Please enter a word: "))
except ValueError:
print ("Wrong Input...")
else:
goodvalue=True
word=word.lower()
List=list(map(str,word))
lenList=len(list(map(str,word)))
listofans=[]
x=0
while (lenList-1==x):
if List[x]==str("a"):
listofans[x]=str("1")
x=x+1
elif List[x]==str("b"):
listofans[x]=str("2")
x=x+1
elif List[x]==str("c"):
listofans[x]=str("3")
x=x+1
It continues like that for all alphabets for a while... And then:
sumofnums=listofans[0]
y=1
while (lenList-2==y):
sumofnums+=listofans[y]
print ("The number is: ", sumofnums)
So basically, if I give hello, it should return 8 5 12 12 15. Any help is truly appreciated!

Your code is very messy, and some of it isn't even needed (all those uses of map is not needed. Nor is the try/except structure)
Why not simplify it a bit ;).
>>> import string
>>> d = {j:i for i, j in enumerate(string.lowercase, 1)}
>>> for i in 'hello':
... print d[i],
...
8 5 12 12 15
Some problems with your code:
Don't compare booleans like that. Just do while goodvalue.
List=list(map(str,word)) is excessive. A simple List = list(word) is needed, but you probably won't even need this as you can iterate through strings (as I have shown above)
str("a") is pointless. "a" is already a string, thus str() does nothing here.
As I said before, the try/except is not needed. No input could cause a ValueError. (unless you meant int())

Are looking for something like this?
[ord(letter)-ord('a')+1 for letter in word]
For "hello" this outputs:
[8, 5, 12, 12, 15]
The ord function returns the ascii ordinal value for the letter. Subtracting ord('a') rebases that to 0, but you have 'a' mapping to 1, so it has to be adjusted by 1.

Try this:
goodvalue=False
while (goodvalue==False):
try:
word=str(input("Please enter a word: "))
except ValueError:
print ("Wrong Input...")
else:
goodvalue=True
word=word.lower()
wordtofans=[]
for c in word:
if c >= 'a' and c <= 'z':
wordtofans.append( int(ord(c)-ord('a')+1) )
print wordtofans
You can directly iterate a string in a for loop, you don't have to convert your string to a list.
You have a control check here to ensure that only letters a..z and A..Z are converted into numbers.
Conversion from a string letter to a number is done using int(ord(c)-ord('a')+1) which uses ord function that will return a ASCII value for a supplied character.

First of all just for make your code smaller you have to look on a small stuff like, instead of print =="a" you print ==str("a"). That's wrong.
So here is your old while loop:
while (lenList-1==x):
if List[x]==str("a"):
listofans[x]=str("1")
x=x+1
elif List[x]==str("b"):
listofans[x]=str("2")
x=x+1
elif List[x]==str("c"):
listofans[x]=str("3")
x=x+1
And here is new:
while (lenList-1==x):
if List[x]=="a":
listofans[x]="1"
x=x+1
elif List[x]=="b":
listofans[x]="2"
x=x+1
elif List[x]=="c":
listofans[x]="3"
x=x+1
And about your question, here is a solution:
[ord(string)-ord('a')+1 for string in word]
If you print "hello" this will returns you:
[8, 5, 12, 12, 15]

Related

How can I assign a string a range of numbers?

If I wanted mystring = (any number between 0-9) is there any way to assign a value like this to a string?
If I had something similar to this :
mystring = "7676-[0-9]-*"
I would want this in theory to be equal to 7676-5-0 and also 7676-9-100 etc.
The reason I want this is because later in my script I will be writing a conditional statement such as:
if mystring == yourstring:
print('something cool')
else:
print('not cool')
where yourstring is equal to a number such as 7676-3-898 where it would equal mystring or 7777-7-8 where it would not equal mystring
You are looking for regex.
As an example, here is something that should be working for you:
import re
# 7676 + one digit between 0 and 9 + at least one digit between 0 and 9 (can be more)
pattern = "7676-[0-9]-[0-9]+"
and later in your code:
if re.match(pattern, "7676-9-100"):
print("something cool")
else:
print("not cool")
Alternative to regex version, you can achieve this in Pythonic way using split() function in Python:
mystring = "7676-5-*"
if '0' <= mystring.split('-')[1] <= '9':
print('something cool')
else:
print('not cool')

Adding numbers in a string

I have a string as an input for the code I'm writing and let an example of the string be:
"12 inches makes 1 foot"
My goal is to have my code run through this string and just pull out the integers and add them. So the output for the string above would be 13. I am using try and except in here as well since another sample input string could be something like "pi is 3.14".
msg= "12 inches makes 1 foot"
thesum = 0
s= msg.split()
for a in s:
try:
if a == int(a):
a= int(a)
thesum += a
print (thesum)
except ValueError as e:
print("Value Error: no int present")
I did what is above and I am not getting it to add the value of a (if it is an int) to "thesum". How can I get this to work? Also, I do want to have it in the try, except format so that I can call the ValueError
There is no need to check equality with a string. In fact, just try '4' == 4 in an interpreter. The answer is False because strings and integers are never equivalent. Just put thesum += int(a) into the loop instead of your if statement. If you don't want try-except, use if a.isdigit(): instead of try: and take out except: altogether:
for a in s:
if a.isdigit():
thesum += int(a)
print(thesum)
A good way would be the combination of several built-ins:
string = "12 inches makes 1 foot"
total = sum(map(int, filter(str.isdigit, string.split())))
filter() finds only the characters that are digits. We then convert each to an integer with map() and find the total with sum().
a is str, and int(a) is int(if possible), so a == int(a) will never equal.
just add the value of int(a), if the convert fails, it will raise ValueError.
The following codes should work.
msg= "12 inches makes 1 foot"
thesum = 0
s= msg.split()
for a in s:
try:
thesum += int(a)
except ValueError as e:
print a
print thesum
I like "re" and comprehension to make it easier to read:
import re
print(sum(int(a) for a in re.findall(r'\d+', '12 inches make 1 foot')))
Then you can extend the regular expression for floats, etc.
Most of the earlier approaches discount the second input which is "pi is 3.14". Although question has been asked with stated assertion of parsing integer. It requires treatment of numbers as float to successfully process second input.
import unittest
import re
def isDigit(s):
return re.match(r'[\d.]+', s)
def stringParse(input):
input = [i.strip() for i in input.split()]
input = filter(lambda x: isDigit(x), input)
input = map(lambda x: float(x), input)
return sum(input)
class TestIntegerMethods(unittest.TestCase):
def test_inches(self):
self.assertEqual(stringParse("12 inches makes 1 foot"), 13.0)
def test_pi(self):
self.assertTrue(stringParse('pi is 3.14'), 3.14)
if __name__ == '__main__':
unittest.main()
Another take on the problem

Printing odd numbered characters in a string without string slicing?

I'm currently doing a project for my university, and one of the assignments was to get python to only print the odd characters in a string, when I looked this up all I could find were string slicing solutions which I was told not to use to complete this task. I was also told to use a loop for this as well. Please help, thank you in advance.
Here is my code so far, it prints the string in each individual character using a for loop, and I need to modify it so that it prints the odd characters.
i = input("Please insert characters: ")
for character in i:
print(character)
Please follow this code to print odd numbered characters
#Read Input String
i = input("Please insert characters: ")
#Index through the entire string
for index in range(len(i)):
#Check if odd
if(index % 2 != 0):
#print odd characters
print(i[index])
Another option:
a= 'this is my code'
count = 1
for each in list(a):
if count % 2 != 0:
print(each)
count+=1
else:
count+=1
I think more information would be helpful to answer this question. It is not clear to me whether the string only contains numbers. Anyway, maybe this answers your question.
string = '38566593'
for num in string:
if int(num) % 2 == 1:
print(num)
To extend on Kyrubas's answer, you could use-
string = '38566593'
for i, char in enumerate(string):
if i % 2 == 1:
print(char)
person = raw_input("Enter your name: ")
a = 1
print"hello " , person
print "total : " , len(person)
for each in list (person):
if a % 2 ==0:
print "even chars : " , (each)
a+=1
else:
a+=1
s = raw_input()
even_string=''
odd_string=''
for index in range(len(s)):
if index % 2 != 0:
odd_string = odd_string+s[index]
else:
even_string = even_string+ (s[index])
print even_string,odd_string
Try this code. For even index start you can use range(0, len(s), 2).
s = input()
res = ''
for i in range(1,len(s),2):
res +=s[i]
print(res)
When we want to split a string, we can use the syntax:
str[beg:end:jump]
When we put just one number, this number indicates the index.
When we put just two numbers, the first indicates the first character (included) and the second, the last character (excluded) of the substring
You can just read the string and print it like this:
i = input("Please insert characters: ")
print(i[::2])
When you put str[::] the return is all the string (from 0 to len(str)), the last number means the jump you want to take, that meaning that you will print the characters 0, 2, 4, etc
You can use gapped index calling. s[start:end:gap]
s = 'abcdefgh'
print(s[::2])
# 'aceg'
returning the characters with indexes 0, 2, 4, and 6. It starts from position 0 to the end and continues with a gap of 2.
print(s[1::2])
# 'bdfh'
Returning the characters with indexes 1, 3, 5, and 7. It starts from position 1 and goes with a gap of 2.

Print two appearances of character found in python list

First time here (and a programming noob), hope I get the formatting correct!
I'm trying to make a function that will print out where in a list the occurence of a sought after letter is placed. The code below finds the letter and prints out where in the list the letter is i.e. if you search for 'a' the program will answer it's in the 2nd spot (x+1).
The problem is, if I search for a letter that have more than one occurrencies (for example the letter 'e'), the program finds the letter in both spots but in both cases prints out that it is in the 10th spot.
I'm trying to find out why, should be 10th and 17th in this case.
# store string in variable
solution = list('can you guess me')
guess = raw_input('What letter do you guess on? ')
# Search list
def search(guess):
nothing = 0
for x in solution:
if x == guess:
print x,
print "is in ",
print solution.index(x) + 1
nothing = 1
if nothing == 0:
print "Couldn't find ",
print guess
search(guess)
If choosing e, like this:
What letter do you think is in the answer? e
the program prints out:
e is in 11
e is in 11
I would like to know why. :/
How about this approach:
solution = 'This is the solution'
# Search list
def search(guess):
return [i for i,x in enumerate(solution) if x == guess]
guess = raw_input('Enter your guess: ')
result = search(guess)
if result:
positions = ','.join(str(i+1) for i in result)
print('{0} was found in positions {1}'.format(guess, positions))
else:
print('Sorry, {0} was not found!'.format(guess))
What we are doing here is stepping through the solution and if a character matches the guess, we return its position. If no characters match, then the method will return an empty list; which is a falsey value.
Then, we just check the return value of the method. If it is a list, we add 1 to the position (since list indices start from 0), and then print those out.
solution.index(x) does the same search for you, but will only ever return the first match.
Use enumerate() instead to create an index:
for i, x in enumerate(solution):
if x == guess:
print x,
print "is in ",
print i + 1
nothing = 1
The alternative approach would be to tell solution.index() where to start searching from. The previous position you printed, for example:
last = -1
for x in solution:
if x == guess:
print x,
print "is in ",
last = solution.index(x, last) + 1
print last
nothing = 1

Palindrome in Python

fno = input()
myList = list(fno)
sum = 0
for i in range(len(fno)):
if myList[0:] == myList[:0]:
continue
print (myList)
I want to make a number palindrome.
eg:
input(123)
print(You are wrong)
input(12121)
print(you are right)
Please Guide me how to make a palindrome in python.Its not complete code please suggest me what the next step.
Thanks
I presume, given your code, you want to check for a palindrome, not make one.
There are a number of issues with your code, but in short, it can be reduced down to
word = input()
if word == "".join(reversed(word)):
print("Palidrome")
Let's talk about your code, which doesn't make much sense:
fno = input()
myList = list(fno) #fno will be a string, which is already a sequence, there is no need to make a list.
sum = 0 #This goes unused. What is it for?
for i in range(len(fno)): #You should never loop over a range of a length, just loop over the object itself.
if myList[0:] == myList[:0]: #This checks if the slice from beginning to the end is equal to the slice from the beginning to the beginning (nothing) - this will only be true for an empty string.
continue #And then it does nothing anyway. (I am presuming this was meant to be indented)
print (myList) #This will print the list of the characters from the string.
Slice notation is useful here:
>>> "malayalam"[::-1]
'malayalam'
>>> "hello"[::-1]
'olleh'
See Explain Python's slice notation for a good introduction.
str=input('Enter a String')
print('Original string is : ',str)
rev=str[::-1]
print('the reversed string is : ',rev)
if(str==rev):
print('its palindrome')
else:
print('its not palindrome')
x=raw_input("enter the string")
while True:
if x[0: ]==x[::-1]:
print 'string is palindrome'
break
else:
print 'string is not palindrome'
break

Categories

Resources