I am a beginner python learner. I was wondering if it was possible to create a basic massage encrypting system without using any modules. I want my programm to check and use variable name that is in string.
let's say,
a = 'l'
b = '5'
c = 'o'
x = input("Enter your massage: ")
print(x, 'THE_USER INPUT matching the variable name and values')
I know I can do this with while or if, but it would take forever. Also, how do you separate each string letters before you match the variable.
I am using python 3. Thanks :)
I have no idea if this is what you are trying to do, but here goes:
a = 'l'
b = '5'
c = 'o'
x = input("Enter your message: ")
values = [globals().get(var, '') for var in list(x)]
print "".join(values)
EXAMPLE
Enter your message: abc
l5o
A more appropriate way to do this would likely be:
replacements = { 'a': 'l', 'b': '5', 'c': 'o' }
x = input("Enter your message: ")
print "".join([replacements.get(val, "") for val in x])
use string.translate this is a much more correct way to do what it sounds like you want
from string import maketrans
in_tab = "abcdefghijklmnopqrstuvwxyz "
out_tab = "5QR&*(=-;Wwz%$^##!yY~:123xq"
t = maketrans(in_tab,out_tab)
print ("Hello World".translate(t))
In case you meant substituting every occurrence of a given character by another one, have a look at the str.translate function.
You could extend your example code as follows:
import string
in = input("Enter your message: ")
mapping = string.maketrans('abc', '15o')
out = in.translate(mapping)
print(out)
Every a is substituted by a 1, every b by 5, every c by o.
Related
I am pretty new to python and would like to know how to write a program that asks the user to enter a string that contains the letter "a". Then, on the first line, the program should print the part of the string up to and including the certain letter, and on the second line should be the rest of the string.
For example...
Enter a word: Buffalo
Buffa
lo
This is what I have so far :
text = raw_input("Type something: ")
left_text = text.partition("a")[0]
print left_text
So, I have figured out the first part of printing the string all the way up to the certain letter but then don't know how to print the remaining part of the string.
Any help would be appreciated
If what you want is the first occurrence of a certain character, you can use str.find for that. Then, just cur the string into two pieces based on that index!
In python 3:
split_char = 'a'
text = input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print(left, '\n', right)
I don't have a python2 on hand to make sure, but I assume this should work on python 2:
split_char = 'a'
text = raw_input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print left + '\n' + right)
Another option that is far more concise is to use
left_text, sep, right_text = text.partition("a")
print (left_text + sep, '\n', right_text)
and then as suggested in the comments, thanks #AChampion !
You should have some knowledge about slicing and concatenating string or list. You can learn them here Slicing and Concatenating
word = raw_input('Enter word:') # raw_input in python 2.x and input in python 3.x
split_word = raw_input('Split at: ')
splitting = word.partition(split_word)
'''Here lets assume,
word = 'buffalo'
split_word = 'a'
Then, splitting variable returns list, storing three value,
['buff', 'a', 'lo']
To get your desire output you need to do some slicing and concatenate some value .
'''
output = '{}\n{}'.join(splitting[0] + splitting[1], splitting[2])
print(output)
First find the indices of the character in the given string, then print the string accordingly using the indices.
Python 3
string=input("Enter string")
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
indices=find(string, "a")
for index in indices[::-1]:
print(string[:index+1])
print(string[indices[-1]+1:])
For my comp sci class I was assigned to make an english to pirate dictionary. The user is prompted to enter a sentence which is then translated to pirate but it isn't working and I'm not sure why. Any help would be appreciated.
eng2pir = {}
eng2pir['sir'] = 'matey'
eng2pir['hotel'] = 'fleabag inn'
eng2pir['restauraunt'] = 'galley'
eng2pir['your'] = 'yer'
eng2pir['hello'] = 'avast'
eng2pir['is'] = 'be'
eng2pir['professor'] = 'foul blaggart'
a = input("Please enter a sentence to be translated into pirate: ")
for x in range(len(a)):
b = a.replace(x, eng2pir[x])
print(b)
Your loop is iterating over range(len(a)), so x will take on an integer value for each individual character in your input. This is off for a couple of reasons:
Your goal is to iterate over words, not characters.
Indexing the dictionary should be done with words, not integers (this is the cause of your error).
Finally, note that .replace() replaces the first occurrence of the searched item in the string. To revise your approach to this problem in a way that still uses that method, consider these two main changes:
Iterate over the keys of the dictionary; the words that could potentially be replaced.
Loop until no such words exist in the input, since replace only does individual changes.
You're iterating over each of the characters in the string input, as the other answer before this has said, replace only replaces the first occurence.
You'd want to do something like this (after you've made your dictionary).
a = input("Please enter a sentence to be translated into pirate: ")
for x in eng2pir:
while x in a:
a = a.replace(x,eng2pir[x])
print(a)
for x in range(len(a)):
b = a.replace(x, eng2pir[x])
because for loop x is int
but eng2pir dict no int key
so output error
#!/usr/bin/env python
# coding:utf-8
'''黄哥Python'''
eng2pir = {}
eng2pir['sir'] = 'matey'
eng2pir['hotel'] = 'fleabag inn'
eng2pir['restauraunt'] = 'galley'
eng2pir['your'] = 'yer'
eng2pir['hello'] = 'avast'
eng2pir['is'] = 'be'
eng2pir['professor'] = 'foul blaggart'
a = input("Please enter a sentence to be translated into pirate:\n ")
lst = a.split()
b = ''
for word in lst:
b += eng2pir.get(word, "")
print(b)
is42= False
while(raw_input()):
d = _
if d == 42:
is42 = True
if not is42:
print d
for this python block of code I want to use outside of the interactive prompt mode. So I can't use _ as the last output. How do I assign raw_input to a variable? I'm doing an exercise off a site. about 5 values is the input and I'm suppose to spit some output out for each corresponding input value. What's the best way to take in this input to do that?
This appears to be very inefficient logic. Do you really need the is42 status flag as well? If not, you might want something like
stuff = raw_input()
while stuff:
if stuff != "42":
print stuff
stuff = raw_input()
Does that fix enough of your troubles?
Hi and welcome to Python!
The raw_input() function returns the input read as a string. So where you have d = _, you can replace that with d = raw_input(). A question I have for you is why you had it inside the while condition? If you wanted it to keep asking the user for a number over and over, then replace while(raw_input()): with while True:.
One more thing, raw_input() always returns a string. So if you run print '30' == 30, you'll see that a string representation of 30 is not equal to the number representation of 30. But that's not a problem! You can turn the return value of raw_input() into an integer type by replacing d = raw_input() with d = int(raw_input()).
Now there will be another problem when the user gives you an input that can't be converted to an integer, but handling that can be an exercise for you. :)
Final code:
is42= False
while True:
d = int(raw_input())
if d == 42:
is42 = True
if not is42:
print d
is42=False
while(!is42):
d = int(raw_input("Enter a number: "))
is42 = d==42
print "d = ", d
That should do it if I understand the requirements of your problem correctly.
This is a simple encryption code that I've come up with. It uses a single character key.
ar = input('please input string to be de/encrypted:')
key = input('please input single character key:')
def encrypt1(key,ar):
i = 0
while i < len(ar):
br = chr(ord(ar[i])^ord(key))
i = i+1
print(br)
encrypt1(key,ar)
print('Input string = ' + ar+'\n'+'key = '+key)
If I input "CMPUT" for the string to be encrypted and 'a' as the key I will get this printed output:
"
,
1
4
5
Which is the correct encryption (according to my assignment example). Now I just have to get those outputs into a single string and print them in the shell like such:
>>>decrypted string: ",145
I've looked through google and old questions on this website but I've still come up empty. I would appreciate your help.
Check out this code, I believe this is what you need (I changed print(br) line):
ar = input('please input string to be de/encrypted:')
key = input('please input single character key:')
def encrypt1(key,ar):
i = 0
while i < len(ar):
br = chr(ord(ar[i])^ord(key))
i = i+1
print(br, end='')
encrypt1(key,ar)
print('\nInput string = ' + ar+'\n'+'key = '+key)
Most obvious way for a beginner would be to simply accumulate to a string
def encrypt1(key,ar):
i = 0
result = ""
while i < len(ar):
br = chr(ord(ar[i])^ord(key))
i = i+1
result += br
return result
Usually you would just write it using a generator expression
def encrypt1(key,ar):
return ''.join(chr(ord(i) ^ ord(key)) for i in ar)
I went through a couple of converters in python but they entered the int value seperately. If the input is 100C i want the output in F and if its 50F i want it in C. I'm new to python and tried some simple lines but the error says its impossible to concatenate str and int.
a = raw_input(" enter here")
char = "f"
char2 = "c"
for s in a:
if s in char:
b=(5*(a-32))/9
print(b,"c")
continue
elif s in char2:
d = (9*a/5)+32
print(d,"f")
continue
Since the user will enter a number followed by the unit, you need to only check if the last character of the string to understand which conversion to do.
You can use slicing, here is an example:
>>> a = '45F'
>>> a[-1]
'F'
>>> a[:-1]
'45'
Of course '45' is a string not a number, converting it to a number with int() will allow you do math on it.
Putting all that together, we have something like this:
a = raw_input('Enter here: ')
number = int(a[:-1])
letter = a[-1].lower()
if letter == 'f':
print('{} in C is {}'.format(a, 5*(number-32)/9))
if letter == 'c':
print('{} in F is {}'.format(a, 9*(number/5)*32))