A converter that converts a string to a different string - python-3.x

Okay it's really complicated to explain, input required, user is typing his input and then it prints what he said but each character is replaced with another character (not random, each symbol will equal a symbol, for example "a" will be "9". Like this) so if I put the input "a" it will return "9", let's say "b" = "5" and "c" = "$". So my if my input is abc (can be ABC it doesn't matter, it will do the .upper), it will print "95$". Like an encoder, each symbol will equal to something and then it will know what to return. I wasn't really sure if it is clear, let me know what isn't clear and I'll make sure to respond as quickly as possible. I tried doing some things but it's a bit hard, I'm still a beginner and that's how I learn. Thanks a lot!
EDIT
A better example:
asking for input,
input: abc,
output: 95$

You can create a dictionary (dict).
my_encoder = dict({"a":"9", "b":"5","c":"$"})
How to use:
value = my_encoder["a"]
print(value) # 9
In your case for a input of abc:
input = "abc"
encoded_input = ""
for character in input:
encoded_input = encoded_input + my_encoder[character]
print(encoded_input) # 95$

Python strs have a built-in translate function. Pass in a dictionary of {<code point>:<replacement>}. In the case of what you've shown, you could do:
print(input().upper().translate({65:'9',66:'5',67:'$'}))
If you have a lot of mappings to do, you can use the str#maketrans static method with two strings of equal length.
trans = str.maketrans('ABC', '95$')
print(input().upper().translate(trans))

Related

Python ord() and chr()

I have:
txt = input('What is your sentence? ')
list = [0]*128
for x in txt:
list[ord(x)] += 1
for x in list:
if x >= 1:
print(chr(list.index(x)) * x)
As per my understanding this should just output every letter in a sentence like:
))
111
3333
etc.
For the string "aB)a2a2a2)" the output is correct:
))
222
B
aaaa
For the string "aB)a2a2a2" the output is wrong:
)
222
)
aaaa
I feel like all my bases are covered but I'm not sure what's wrong with this code.
When you do list.index(x), you're searching the list for the first index that value appears. That's not actually what you want though, you want the specific index of the value you just read, even if the same value occurs somewhere else earlier in the list too.
The best way to get indexes along side values from a sequence is with enuemerate:
for i, x in enumerate(list):
if x >= 1:
print(chr(i) * x)
That should get you the output you want, but there are several other things that would make your code easier to read and understand. First of all, using list as a variable name is a very bad idea, as that will shadow the builtin list type's name in your namespace. That makes it very confusing for anyone reading your code, and you even confuse yourself if you want to use the normal list for some purpose and don't remember you've already used it for a variable of your own.
The other issue is also about variable names, but it's a bit more subtle. Your two loops both use a loop variable named x, but the meaning of the value is different each time. The first loop is over the characters in the input string, while the latter loop is over the counts of each character. Using meaningful variables would make things a lot clearer.
Here's a combination of all my suggested fixes together:
text = input('What is your sentence? ')
counts = [0]*128
for character in text:
counts[ord(character)] += 1
for index, count in enumerate(counts):
if count >= 1:
print(chr(index) * count)

String Operations Confusion? ELI5

I'm extremely new to python and I have no idea why this code gives me this output. I tried searching around for an answer but couldn't find anything because I'm not sure what to search for.
An explain-like-I'm-5 explanation would be greatly appreciated
astring = "hello world"
print(astring[3:7:2])
This gives me : "l"
Also
astring = "hello world"
print(astring[3:7:3])
gives me : "lw"
I can't wrap my head around why.
This is string slicing in python.
Slicing is similar to regular string indexing, but it can return a just a section of a string.
Using two parameters in a slice, such as [a:b] will return a string of characters, starting at index a up to, but not including, index b.
For example:
"abcdefg"[2:6] would return "cdef"
Using three parameters performs a similar function, but the slice will only return the character after a chosen gap. For example [2:6:2] will return every second character beginning at index 2, up to index 5.
ie "abcdefg"[2:6:2] will return ce, as it only counts every second character.
In your case, astring[3:7:3], the slice begins at index 3 (the second l) and moves forward the specified 3 characters (the third parameter) to w. It then stops at index 7, returning lw.
In fact when using only two parameters, the third defaults to 1, so astring[2:5] is the same as astring[2:5:1].
Python Central has some more detailed explanations of cutting and slicing strings in python.
I have a feeling you are over complicating this slightly.
Since the string astring is set statically you could more easily do the following:
# Sets the characters for the letters in the consistency of the word
letter-one = "h"
letter-two = "e"
letter-three = "l"
letter-four = "l"
letter-six = "o"
letter-7 = " "
letter-8 = "w"
letter-9 = "o"
letter-10 = "r"
letter11 = "l"
lettertwelve = "d"
# Tells the python which of the character letters that you want to have on the print screen
print(letter-three + letter-7 + letter-three)
This way its much more easily readable to human users and it should mitigate your error.

Python get character position matches between 2 strings

I'm looking to encode text using a custom alphabet, while I have a decoder for such a thing, I'm finding encoding more difficult.
Attempted string.find, string.index, itertools and several loop attempts. I would like to take the position, convert it to integers to add to a list. I know its something simple I'm overlooking, and all of these options will probably yield a way for me to get the desired results, I'm just hitting a roadblock for some reason.
alphabet = '''h8*jklmnbYw99iqplnou b'''
toencode = 'You win'
I would like the outcome to append to a list with the integer position of the match between the 2 string. I imagine the output to look similar to this:
[9,18,19,20,10,13,17]
Ok, I just tried a bit harder and got this working. For anyone who ever wants to reference this, I did the following:
newlist = []
for p in enumerate(flagtext):
for x in enumerate(alphabet):
if p[1] == x[1]:
newlist.append(x[0])
print newlist

Dictionary thesaurus replacing substrings

So I have a dictionary that contains words and their synonyms. The purpose is to replace substrings in a string with a random synonym. Here's my code.
import random
thesaurus = {
"happy":["glad", "blissful", "ecstatic", "at ease"],
"sad" :["bleak", "blue", "depressed"]
}
phrase = input("Enter a phrase: ")
for x in phrase.split():
if x in thesaurus:
ran = len(thesaurus[x])
print( len(thesaurus[x]))
ranlis = random.randint(0,ran - 1)
phrase = phrase.replace(x,str.upper(thesaurus[x][ranlis]))
print(phrase)
If I input "happy happy happy"
The output is:
ECSTATIC ECSTATIC ECSTATIC
I want it to print a different synonym each time(or at least be able to. I understand that it is random).
So:
ECSTATIC BLISSFUL AT EASE
I understand the error in my logic but am unsure how to fix it.
The key is to replace only one occurrence. The replace() function takes 3 parameters, the third being the number of occurrences you want to replace.
So:
phrase = phrase.replace(x,str.upper(thesaurus[x][ranlis]),1)

decompressing a compressed string

My question is that I don't know where to go now with the code I have to create a decompress code. I get the error (TypeError: can't multiply sequence by non-int of type 'str') and assume its because I'm not multiplying the string correctly. Also, I can't use lists, just string manipulation for this assignment
Just as an example, the output's suppose to look like this-> cat2dog1qwerty3 -> catcatdogqwertyqwertyqwerty
Function:
def decompress(compressed_in):
new_word = True
char_holder = ""
decompressed_out = ""
for char in compressed_in:
if char.isalpha and new_word:
char_holder += char
new_word = False
elif char.isalnum:
decompressed_out += char * char_holder
new_word = True
return decompressed_out
Main:
# Import
from compress import decompress
# Inputs
compressed_in = str(input("Enter a compressed string: ")) # compressed
# Outputs
decompressed_out = decompress(compressed_in)
print(decompressed_out)
Since this is apparently a homework assignment, I won't give you the code, but here are several problems I see with what you're presented.
Indentation. This is probably an artifact of copying-and-pasting, but every line after the def should be indented.
Not calling functions. When you write char.isalpha, that probably isn't doing what you want it to. .isalpha() is a function, so you need to call it with parentheses, like char.isalpha().
isalnum() is probably not the function you want. That checks if something is a letter or a number, but you've already checked for letters, so you probably want the function that checks if something is a number. This isn't strictly necessary, since the other if condition will still trigger first, but it's something you could get marked down for.
You never clear char_holder. It looks like you meant to, since you have a boolean new_word that you keep track of, but you aren't using it properly. At some point, you should be doing char_holder = char (ie. not +=). I'll let you decide where to put that logic.
Finally, for the error you're getting. You are correct that you are not multiplying things together correctly. Think about what the types are in the multiplication statement, and what values the variables would have. For example, in the first pass, char_holder would be equal to 'cat', and char would be equal to '3'. Try typing '3' * 'cat' into a Python interpreter and see what happens. It should be evident from here what you need to do to fix this.

Resources