So I'm trying to make a program that allows you to decode messages in python. Here's what I got so far...
def decode():
print("Let's see what she wanted to tell you.")
time.sleep(2)
messageOne= raw_input('Please paste the message: ')
print("Decoding message now...")
message= list(messageOne)
and I was wondering how I would take the individual letters in the list and change them based on the code I want. Aka I need to know how to change a specific value in the list. Thanks!
Your question isn't very clear, based on what I see you can have different ways of replacing letters. For example let's use string s:
>>> s = 'Hello'
>>> s.replace('l','h')
Hehho
If you only want to replace one occurrence of a given letter use this:
>>> s = 'Hello'
>>> s.replace('l','h', 1) #will only replace the first occurrence
Hehlo
You can also convert your string into a list
>>> s = 'Hello'
>>> s = [x for x in s]
>>> s
['H', 'e', 'l', 'l', 'o']
In here you can replace anything by anything, like so:
>>> s[3] = 'h'
>>> s
['H', 'e', 'l', 'h', 'o']
When you're done with replacing whatever you want, you can use the .join() method to make your list a string again like so:
>>> s = ''.join(s) #separator goes in between the quotes
>>> s
Helho
Related
My purpose is to get an input as a string and return a list of lower case letters of that string, without repeats, without punctuations, in alphabetical order. For example, the input "happy!" would get ['a','h','p','y']. I try to use the join function to get rid of my punctuations but somehow it doesn't work. Does anybody know why? Also, can sort.() sort alphabets? Am I using it in the right way? Thanks!
def split(a):
a.lower()
return [char for char in a]
def f(a):
i=split(a)
s=set(i)
l=list(s)
v=l.join(u for u in l if u not in ("?", ".", ";", ":", "!"))
v.sort()
return v
.join() is a string method, but being used on a list, so the code raises an exception, but join and isn't really needed here.
You're on the right track with set(). It only stores unique items, so create a set of your input and compute the intersection(&) with lower case letters. Sort the result:
>>> import string
>>> s = 'Happy!'
>>> sorted(set(s.lower()) & set(string.ascii_lowercase))
['a', 'h', 'p', 'y']
You could use:
def f(a):
return sorted(set(a.lower().strip('?.;:!')))
>>> f('Happy!')
['a', 'h', 'p', 'y']
You could also use regex for this:
pattern = re.compile(r'[^a-z]')
string = 'Hello# W0rld!!##'
print(sorted(set(pattern.sub('', string))))
Output:
['d', 'e', 'l', 'o', 'r']
How do I check if a sequence of characters exists in a list?
I have a string with some characters that have sequences that reoccur. I know that strings are immutable so I turn the string into the list. However, I'm not sure how to iterate through the list, find the occurrence and change the first letter of the occurrence.
message: DDMCAXQVEKGYBNDDMZUH
Occurence is: DDM
list: ['D', 'D', 'M', 'C', 'A', 'X', 'Q', 'V', 'E', 'K', 'G', 'Y', 'B', 'N', 'D', 'D', 'M', 'Z', 'U', 'H']
What I have currently is simply turning the message into the list. I've tried different ways, which were unsuccessfully that's what I didn't post it. Not really asking you to write the code but at the least explain how to achieve this.
It's a lot easier to check if a string exists in another string since you can simply use the in operator:
if 'DDM' in message:
# do something
But since your goal is to change the first letter of the occurrence, you can use the str.index method to obtain the index of the occurrence and then assemble a new string with slices of the current string and the new letter:
try:
i = message.index('DDM')
message = message[:i] + new_letter + message[i + 1:]
except ValueError:
raise RuntimeError("Sequence 'DDM' not found in message.")
You can use re.sub():
import re
s = 'DDMCAXQVEKGYBNDDMZUH'
re.sub(r'DDM', '$DM', s)
# $DMCAXQVEKGYBN$DMZUH
A simple solution with a for-loop would be:
msg = 'DDMCAXQVEKGYBNDDMZUH'
occ = 'DDM'
for i in range(len(msg)):
if msg[i:i+len(occ)] == occ:
msg = msg[:i] + 'x' + msg[i+1:]
resulting in xDMCAXQVEKGYBNxDMZUH
This also works with overlapping substrings. For example:
msg = 'AAABAA'
occ = 'AA'
will give xxABxA
The simplest way would be using string replace() function.
string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
message = "DDMCAXQVEKGYBNDDMZUH"
print message.replace("DDM", "ABC", 1)
Replace function would replace the first occurrence of DDM in the message string.
output: ABCCAXQVEKGYBNDDMZUH
If I carefully read your question you want to search the first occurrence of DDM in your message and replace the first character of it. In that case use below:
message = "DDMCAXQVEKGYBNDDMZUH"
print message.replace("DDM", "ADM", 1)
output: ADMCAXQVEKGYBNDDMZUH
This question already has answers here:
Replacing one character of a string in python
(6 answers)
Closed 5 years ago.
I am working in Python right now.
My ch variable, which is the character variable has a character store in it, which has been entered by the user.
I also have a string variable (string1) in which I want to add the character without over-writing the string variable.
i.e I want to do string1[i]=ch, where i can be any position.
when i do this in python, it gives an error saying: 'str' object does not support item assignment.
here, string1[i]=ch, is in a while loop.
Is there a proper way of doing this? Please help.
str in python is immutable. That means, you can't assign some random value to a specific index.
For example, below is not possible:
a = 'hello'
a[2]= 'X'
There is an workaround.
make a list from the str.
mutate the specific index you wanted from that list.
form a str again from the list.
Like below:
>>> a = 'hello'
>>> tmp_list = list(a)
>>> tmp_list
['h', 'e', 'l', 'l', 'o']
>>> tmp_list[2] = 'X'
>>> tmp_list
['h', 'e', 'X', 'l', 'o']
>>>
>>> a = ''.join(tmp_list)
>>> a
'heXlo'
How does the following output come?
>>> a
'hello'
>>> a = list(a)
>>> a
['h', 'e', 'l', 'l', 'o']
>>> a = str(a)
>>> a
"['h', 'e', 'l', 'l', 'o']"
>>> a.title()
"['H', 'E', 'L', 'L', 'O']"
>>> a[0]
'['
>>> a[1]
"'"
>>> a[2]
'h'
When title has to capitalize only the first letter of the string, how does every letter get capitalized?
str() does not join a list of individual characters back together into a single string. You'd use str.join() for that:
>>> a = list('hello')
>>> ''.join(a)
'hello'
str(listobject) returns a string representation of the list object, not the original string you converted to a list. The string representation is a debug tool; text you can, for the most part, paste back into a Python interpreter and have it recreate the original data.
If you wanted to capitalise just the first characters, use str.title() directly on the original string:
>>> 'hello'.title()
'Hello'
>>> 'hello world'.title()
'Hello World'
I think you're confused about how title works.
In [5]: s = "hello there"
In [6]: s.title()
Out[6]: 'Hello There'
See how it capitalises the first letter of each word? When you str() the list, it no longer sees hello as a single word. Instead, it sees each letter on its own and decides to capitalise each letter.
>>> a=list('hello')
>>> str(a)
"['h', 'e', 'l', 'l', 'o']"
>>> len(str(a))
25
So you have a string of 25 characters. All those ',, etc. are part of the string. title sees 5 one-character words, so each one is upper cased. Try ''.join instead
>>> ''.join(a)
'hello'
>>> len(''.join(a))
5
>>> ''.join(a).title()
'Hello'
I'm having issues with raw_input again, this time trying to turn the value I get into a list. Here is my code:
original = raw_input("Type is your input? ")
original_as_array = list('original')
print original_as_array
for i in range(0,len(original)):
print i
my print original_as_array literally prints ['o', 'r', 'i'.... etc]. If we pretend that my input is Hello World, I want original_as_array to output: ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o'... etc]. I think I'm making a tiny mistake. Can you point me in the right direction:)?
Quotes form a string literal.
original_as_array = list(original)
original = raw_input("Type is your input? ")
original_as_array = list(original) # no quotes. If you put quotes, you are turning it into a string.
print original_as_array
for i in original_as_array: # this is shorter way to iterate and print than your method
print i
Strings are already iterable, so you don't need to convert it to a list, so you can easily go :
original = raw_input("Type is your input? ")
# or if you really want a list
original_as_list = list(original) # NOT 'original', that's passing the string original not the value of original
for letter in original:
print letter