need help converting string to unicode and then add values - python

I need help converting this code to lower cases, then substring to remove spaces then find the ASCII values then add them up to get a sum, this is what I wrote:
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()

Two problems: (1) After splitting, fullname is now a list of names, so you need a second loop to iterate over the characters, and (2) you typed fullname instead of totalvalue when summing in the loop. Try replacing the loop with:
totalvalue = 0
for name in fullname:
for character in name:
totalvalue += ord(character)

What about something like this where you use a list comprehension:
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()
where values is a list of the ascii values for the string, you can prob do the rest from there

Related

Removing strings character with given input

I need to remove a certain string with the given input. For example,
user_input = input("Input File name: ")
and the user key in "patient_zero[20150203].txt" and it would like to clean up the file name by removing all instances of square brackets and the contents contained within it.
Output should be "patient_zero.txt". Is there anyway to do it?
If you just want to remove the square bracket portion of the filename, you could use:
inp = "patient_zero[20150203].txt"
output = re.sub(r'^(\S+)\[.*?\]\.(\S+)$', r'\1.\2', inp)
print(output) # patient_zero.txt
using spplit
var = "patient_zero[20150203].txt"
print(var.split("[")[0] + var.split("]")[1]) # PatientName + FileFormat
import re
s = "patient_zero[20150203].txt"
print (re.sub(r'\[[\w\s]+\]','',s))
Output:
patient_zero.txt

How to print multiple values from for loop inside print statement in a single line?

My Code has something like:
user = input("Enter username: ")
I have 10 variables like:
ch1 = "String1"
ch2 = "String2"
ch3 = "String3"
ch4 = "String4"
...
Suppose username entered is Pawan my input statement returns me a list:
basic_choices = input("Enter All your choices separated by ',' to perform in your remote system together: ").strip().split(',')
The output is some random numbers from 1 to 10 in a list:
['1','3','7']
Now I want to print a single string in a single line based on the choices of user:
For 1,3,7 is should give the output:
The strings selected by you are String1; String3; String7; in the strings list of Pawan
(semicolon should be included)
I have tried many ways but it doesn't work, either returns the value of only 1st number or it returns the generator object at address
print("The strings selected by you are ch{0}; in the strings list of {1}".format(*basic_choices, user))
print("The strings selected by you are ch{0}; in the strings list of {1}".format(choice, user) for choice in basic choices)</p>
I think it would make sense to just put your "Strings" in a dictionary, where the keys are the possible user inputs. I then used str.join to format the output correctly:
user = 'Pawan'
ch1 = "String1"
ch2 = "String2"
ch3 = "String3"
ch4 = "String4"
ch5 = "String5"
str_options = {'1':ch1,'2':ch2,'3':ch3,'4':ch4,'5':ch5}
basic_choices = input("Enter All your choices separated by ',' to perform in your remote system together: ").strip().split(',')
chosen = [str_options[i] for i in basic_choices]
print("The strings selected by you are " +
"; ".join(chosen) +
"; in the strings list of {}".format(user))
Note that (as is) this will raise an error if the user input is not in the dicitionary.

Finding the smallest number in a .dat file containing multiple data types | Python

Context: I have written a program that asks the user to enter the name and score (integer) for a user-defined quantity of players. The program then formats, slices and stores the values in a file named golf.dat
Issue: I am trying to expand my program to allow it to identify the player with the lowest score and print the name and score of the lowest scorer.
My code:
def playerDataInput(playerQuantity):
outputFile = open("golf.dat", "w")
for currentPlayer in range (1, playerQuantity + 1):
playerName = (input("Please enter player " + format(currentPlayer, "d",)+"'s name: "))
playerScore = (input("Please enter player " + format(currentPlayer, "d",)+"'s score: "))
outputFile.write(playerName + "\n")
outputFile.write(str(playerScore) + "\n")
outputFile.close()
def playerDataOutput():
inputFile = open("golf.dat", "r")
playerName = inputFile.readline()
while playerName != "":
playerScore = inputFile.readline()
playerName = playerName.rstrip("\n")
playerScore = playerScore.rstrip("\n")
print(playerName + ("'s score was:"), playerScore)
playerName = inputFile.readline()
inputFile.close()
def lowestScorer():
integers = open("golf.dat", "r")
lowestScore = 0
for score in integers:
if lowestScore >= int(score.strip()):
lowestScore = int(score.strip())
integers.close()
print("The lowest score was: ", lowestScore)
I've tried: I have tried (in vein) to write a function (lowestScorer) to extract and display the lowest value, but it didn't occur to me at first, but this is obviously going to fail, based on the way my data is stored.
Where you can help: suggest if there is any Pythonic way of adapting my code (rather than re-writing), to allow my program to identify and display the name and scorer of the lowest scorer / integer, saved in my golf.dat file?
My suspicion is that I should have written this program with two lists that hold names and scores respective and then written these to golf.dat (for easy extraction and analysis) or created these two lists (as sublists, thus holding names and integer score values separately) but gone a step further and saved them within a master list.

Converting characters in a variable to their original ascii form

Okay, so I've been doing a lot of research and I couldn't find any answers so I came here to ask for some help.
My problem that I have encountered is I am having trouble taking a variable, then in the background of my code converting each individual string of that variable back to its ascii form and manipulating it using math, such as +, -, * and /. Here is my code..
Note: I had one theory, which is using a for loop to say for each character in this variable, do... blah blah. Here's my code anyways.
import random
import sys
import time
invalid_input = True
def start():
print("Welcome to the Encryption / Decryption Program!")
menuAnswer = input("Please select the number corresponding to the option you would like (1 - 3)\n---------------------------------\n[1] Encrypt\n[2] Decrypt\n[3] Exit the program\n---------------------------------\n")
if menuAnswer == '1':
print("You have chosen to Encrypt!")
invalid_input = False
message = open("sample.txt","r")
msgName = input("What is the name of the text document you would like to Encrypt?\n")
msgName = msgName.upper()
if msgName == 'SAMPLE':
key = '' #This variable will have the encryption key stored inside of it.
for i in range(0,8):
random_number = (random.randint(33,162)) #Generate a random ascii number from the range 33 to 162
key +=str(chr(random_number)) #Convert and store this ascii number as a character to the variable 'Key'
print(key)
print("Remember this key, as you will need it to decrypt your file!")
#\\ Offset //# #Finding the offset, must be able to convert each individual character of the key variable and return it to its usual form to manipulate using math.
else:
print("Invalid Filename")
elif menuAnswer == '2':
print("You have chosen to Decrypt!")
invalid_input = False
elif menuAnswer == '3':
print("You have chosen to exit!")
invalid_input = False
time.sleep(1)
print("Exiting...")
time.sleep(1.5)
exit()
else:
print("Invalid Input, Please try again!")
while invalid_input:
start()
Sorry if this question was difficult to understand, I am really confused myself and have been stuck on this for a week straight.
If I understand correctly you want to convert each character of your string to its ascii number and then do some sort of math operation on it and then convert it back to a string which you can do using ord() like so
s = 'Sample'
tmp = ''
for i in s:
tmp += chr(ord(i)+1)
print tmp
Tbnqmf
Although with the code you have you don't need to convert it to a string and then back to characters to manipulate it you can just manipulate it as soon as you pick a random number like so
import random
def start():
key = ''
for i in range(0,8):
random_number = (random.randint(33,162))
key +=chr(random_number+1)
print(key)
start()
Note you need to be careful when manipulating your characters since you could manipulate it to a number that is not an ascii character

New line for input in Python

I am very new to Python programming (15 minutes) I wanted to make a simple program that would take an input and then print it back out. This is how my code looks.
Number = raw_input("Enter a number")
print Number
How can I make it so a new line follows. I read about using \n but when I tried:
Number = raw_input("Enter a number")\n
print Number
It didn't work.
Put it inside of the quotes:
Number = raw_input("Enter a number\n")
\n is a control character, sort of like a key on the keyboard that you cannot press.
You could also use triple quotes and make a multi-line string:
Number = raw_input("""Enter a number
""")
If you want the input to be on its own line then you could also just
print "Enter a number"
Number = raw_input()
I do this:
print("What is your name?")
name = input("")
print("Hello" , name + "!")
So when I run it and type Bob the whole thing would look like:
What is your name?
Bob
Hello Bob!
# use the print function to ask the question:
print("What is your name?")
# assign the variable name to the input function. It will show in a new line.
your_name = input("")
# repeat for any other variables as needed
It will also work with: your_name = input("What is your name?\n")
in python 3:
#!/usr/bin/python3.7
'''
Read list of numbers and print it
'''
def enter_num():
i = input("Enter the numbers \n")
for a in range(len(i)):
print i[a]
if __name__ == "__main__":
enter_num()
In the python3 this is the following way to take input from user:
For the string:
s=input()
For the integer:
x=int(input())
Taking more than one integer value in the same line (like array):
a=list(map(int,input().split()))

Categories