first symbol not printing but the rest is normally printing - python

I am not sure why the first asterisk is not printing, does anyone have any ideas? BTW I am using a dictionary.
input
error
output
' ****'
expected output
'*****'
MORSE_CODES={'A':'.-','B':'-...','C':'-.-.',
'D':'-..','E':'.','F':'..-.','G':'--.',
'H':'....','I':'..','J':'.---','K':'-.-',
'L':'.-..','M':'--','N':'-.','O':'---',
'P':'.--.','Q':'--.-','R':'.-.',
'S':'...','T':'-','U':'..-','V':'...-',
'W':'.--','X':'-..-','Y':'-.--','Z':'--..'}
def encode_Morse(my_msg):
my_msg_Morse=" "
for letter in my_msg:
if letter!=" " and letter not in MORSE_CODES:
my_msg_Morse+="*"
elif letter!=" ":
my_msg_Morse+= MORSE_CODES[letter]+" "
else:
my_msg_Morse+=" "
my_msg_Morse = my_msg_Morse[:-1]
return my_msg_Morse

The problem is that you are not returning the full string and that the last asterisk is not printing. You can fix this problem by amending the assignment my_msg_Morse = my_msg_Morse[:-1]
to
my_msg_Morse = my_msg_Morse.
If you weren't adding blank spaces with this condition (for the characters matched by your dictionary - i.e. the capital letters)
elif letter!=" ":
my_msg_Morse+= MORSE_CODES[letter]+" "
it would be more clear that you have this problem generally. Consider the test case where you don't add blanks:
Input:
ERROR
Expected Output:
..-..-.---.-.
Actual Output:
..-..-.---.-
However, you are adding blank spaces after each rendering of a capital into morse code. So this loss of the final character (a blank space) is mostly unobserved.
I don't know what your requirements are but if they are satisfied by returning a string with no trailing white space you could return my_msg_Morse.rstrip(). The rstrip() method of the string object removes all trailing white space. This way, you could preserve your within-string white space while eliminating trailing white space. I also like Tim Robert's suggestion (in a comment to your original question) of using a list and joining it.

Related

Swap last two characters in a string, make it lowercase, and add a space

I'm trying to take the last two letters of a string, swap them, make them lowercase, and leave a space in the middle. For some reason the output gives me white space before the word.
For example if input was APPLE then the out put should be e l
It would be nice to also be nice to ignore non string characters so if the word was App3e then the output would be e p
def last_Letters(word):
last_two = word[-2:]
swap = last_two[-1:] + last_two[:1]
for i in swap:
if i.isupper():
swap = swap.lower()
return swap[0]+ " " +swap[1]
word = input(" ")
print(last_Letters(word))
You can try with the following function:
import re
def last_Letters(word):
letters = re.sub(r'\d', '', word)
if len(letters) > 1:
return letters[-1].lower() + ' ' + letters[-2].lower()
return None
It follows these steps:
removes all the digits
if there are at least two characters:
lowers every character
builds the required string by concatenation of the nth letter, a space and the nth-1 letter
and returns the string
returns "None"
Since I said there was a simpler way, here's what I would write:
text = input()
result = ' '.join(reversed([ch.lower() for ch in text if ch.isalpha()][-2:]))
print(result)
How this works:
[ch.lower() for ch in text] creates a list of lowercase characters from some iterable text
adding if ch.isalpha() filters out anything that isn't an alphabetical character
adding [-2:] selects the last two from the preceding sequence
and reversed() takes the sequence and returns an iterable with the elements in reverse
' '.join(some_iterable) will join the characters in the iterable together with spaces in between.
So, result is set to be the last two characters of all of the alphabetical characters in text, in reverse order, separated by a space.
Part of what makes Python so powerful and popular, is that once you learn to read the syntax, the code very naturally tells you exactly what it is doing. If you read out the statement, it is self-describing.

how to remove the first comma of a print statement in python

I have been trying to remove the first two commas of a print statement and am having trouble doing this.
The print statement essentially allows to print the elements of a set without the brackets (using *) and with commas separating the elements (using sep=", ").
Only problem is the first two pieces of the statement (a cross mark and a sentence) also get separated with a comma. This is not desired (as shown in screenshot).
I would like to know how I can remove the comma after the cross mark and the comma after the colon.
FYI: '\033[91m' = red font colour, '\u274C' = cross mark, '\033[0m' = no color
My code is shown below.
print('\033[91m' + '\u274C', "Paragraphs contain unspecified font(s):" + '\033[0m', *invalid_font, sep=", ")
You can either, use two separate print statements.
print('\033[91m\u274C '
'Paragraphs contain unspecified font(s):'
'\033[0m', end='')
print(*invalid_font, sep=", ")
or join the fonts with comma and space.
print('\033[91m\u274C '
'Paragraphs contain unspecified font(s):'
'\033[0m',
', '.join(map(str, invalid_font)))
Edit
As #S3DEV pointed out in the comments, it is unnecessary to map the invalid_font iterable to str if it is already an iterable of str. In this case, you just need
print('\033[91m\u274C '
'Paragraphs contain unspecified font(s):'
'\033[0m',
', '.join(invalid_font))

Ignore space in python

I need this code to ignore (not replace) spaces. Basically, it should capitalise every second letter of the alphabet only.
def spaces(test_space):
text = (str.lower, str.upper)
return ''.join(text[i%2](x) for i, x in enumerate(test_space))
print(spaces('Ignore spaces and other characters'))
print(spaces('Ignore spaces and 3rd characters!'))
Output
iGnOrE SpAcEs aNd oThEr cHaRaCtErS
iGnOrE SpAcEs aNd 3Rd cHaRaCtErS
This sounds like homework, so I'm only going to give suggestions and resources not complete code:
One way to do this would be to:
Replace every space with 2 of some character that can't appear in your text. for example use "$$". This can easily be done via python's replace function. We replace a space with 2 characters because each space is "throwing off" the index by one (mod 2), so by replacing each space by two characters corrects the problem (since 2 (mod 2) = 0).
Capitalize every other character using your current program
Replace each occurrence of '$$' with a space.
Put the spaces back using the indexes you saved
Output: iGnOrE sPaCeS aNd 3rD cHaRaCtErS!
Alternatively, you could iterate through the string (using a loop), keeping a position counter, but use a regex to ignore all non-Alphabet characters in the counter. You could also probably accomplish this succinctly via a list comprehension, although it might be more confusing to read.
def spaces(test_space):
return " ".join(
[
"".join(
char.upper() if i % 2 == 1 else char.lower()
for i, char in enumerate(word)
)
for word in test_space.split()
]
)
outputs
iGnOrE sPaCeS aNd oThEr cHaRaCtErS

Printing multiple newlines with Python

I'm trying to separate some outputted text in Python 3.
Heres sorta an example of what iv got now
print("words")
print("")
print("")
print("")
print("")
print("")
print("")
#(Print would keep going on like 50 times)...
print("more words")
now putting all those prints is annoying and i need the words to be vertically seperated. like this
words
more words
Any ideas on how to separate huge verticle distances.
Thanks :)
You can construct a string of newline characters, which will result in vertical space, like this:
lines = 5 # Number of blank lines
print("\n" * lines)
You could put a newline character "\n" in the string, e.g.
>>> print ("\n\n\n\n")
Characters preceded by a backslash are 'escaped', and are converted to special characters by Python. Some commonly used escape sequences are:
Newline "\n"
Tab "\t"
Carriage Return "\r"
Backslash "\\"
Hexadecimal character code "\x0f"
Quote character "\"" or '\''
Note that strings can be repeated by multiplying them with a number, e.g.
>>> print ("\n" * 100)

spliting the string over separators

can someone please tell me how to fix this? after the last seperator, the code stops and doesn't reach the end of the original string
def split_on_separators(original, separators):
""" (str, str) -> list of str
Return a list of non-empty, non-blank strings from original,
determined by splitting original on any of the separators.
separators is a string of single-character separators.
>>> split_on_separators("Hooray! Finally, we're done.", "!,")
['Hooray', ' Finally', " we're done."]
"""
result = []
newstring=''
for char in original:
if char in separators:
result.append(newstring)
newstring = ""
else:
newstring += char
return result
import re
def split_on_separators(original, separators):
return re.split("[" + separators + "]", original)
OK, this isn't perfect because certain characters cannot appear in separators because it's used to build a regex, but it works for many cases including the one in the question. A more robust way would be to simply use re.split instead of this function in the first place.
You need to append newstring to result once the loop is completed / before you return. Since there are no separators after the last string it will otherwise never get added since only encountering a separator causes appendage to the list.
The code only puts a part of the input string in result when it hits a separator. Since there is no separator at the end of your sample input, the "we're done" in newstring is not appended to result. To fix this you would have add an if statement after the for to see if there was something in newstring, and then append it if necessary.

Categories

Resources