Remove extra space before word ends - python

I need some help removing the extra space before a word/string ends. Does anyone have any ideas?
input:
hello
output I get (two spaces at the end):
' .... . .-.. .-.. --- '
expected output (only one space at the end, but two spaces between letters):
' .... . .-.. .-.. --- '
Here's my code:
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=my_msg.upper()
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+=" "
return my_msg_Morse

You could just do:
my_msg_Morse_list.replace(' ','')
Edited
I was corrected,
If the problem is always two spaces at the maybe you could just trim the string with
my_msg_Morse = my_msg_Morse[:-1]

I would use the split() method on your string to parse out your morse code into an iterable and then iterate over each code, first using strip() and then ignoring empty elements.

You can do this one of two ways:
Keep track of the index of every letter in your iteration using enumerate(). Check if this is the last letter in my_msg. If it is, don't add the second space.
def encode_Morse(my_msg):
my_msg=my_msg.upper()
my_msg_Morse=" "
for index, letter in enumerate(my_msg):
if letter!=" " and letter not in MORSE_CODES:
my_msg_Morse+=" * "
elif letter!=" ":
my_msg_Morse+= MORSE_CODES[letter] + " "
if index < len(my_msg) - 1:
my_msg_Morse += " "
else:
my_msg_Morse+=" "
return my_msg_Morse
Build a list and then use str.join() to join it with spaces. We'll also have to add one space before and after the result of the join().
def encode_Morse(my_msg):
my_msg=my_msg.upper()
my_msg_Morse_list = []
for letter in my_msg:
if letter=" " and letter not in MORSE_CODES:
my_msg_Morse_list.append("*")
elif letter!=" ":
my_msg_Morse_list.append(MORSE_CODES[letter])
else:
my_msg_Morse_list.append(" ")
# Add the leading and trailing space
return " " + " ".join(my_msg_Morse_list) + " "
I'm going to rewrite your function to make the if-else ladder a little more clear. First, I'm going to add a value for a space in the MORSE_CODES dictionary. This eliminates the need to check if letter is a space. Then, I'm going to use the dict.get() function to get the value of the key letter from MORSE_CODES. get() lets us specify a default value to be returned if the given key doesn't exist in the dictionary.
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=my_msg.upper()
my_msg_Morse_list = []
for letter in my_msg:
morse_letter = MORSE_CODES.get(letter, "*")
my_msg_Morse_list.append(morse_letter)
# Add the leading and trailing space
return " " + " ".join(my_msg_Morse_list) + " "
When you do all these things, you can write your entire function in one line if you'd like using a generator expression in place of the loop:
def encode_Morse(my_msg):
return " " + " ".join(MORSE_CODES.get(letter, "*") for letter in my_msg.upper()) + " "
For every function, you can check that it gives the expected output by checking that the following code gives True
' .... . .-.. .-.. --- ' == encode_Morse("hello")

Related

how to remove spaces in between of a string in python?

Suppose I have a string : ' Swarnendu Pal is a good boy '
Here I want to remove all the spaces in between the strings, that means the leading and the last spaces should be remain same but all other spaces should be removed. My final expected output will be : ' SwarnenduPalisagoodboy '
Try this... doesn't matter #spaces you have in the start/end... the code will retain them... & remove in between strings...
s = " Swarnendu Pal is a good boy "
start_space, end_space = 0,0
for i in s:
if i == " ":
start_space += 1
else:
break
for i in s[::-1]:
if i == " ":
end_space += 1
else:
break
result = " " * start_space + s.replace(" ","") + " " * end_space
print(result)
# " SwarnenduPalisagoodboy " #### output
Hope this helps...
An attempt at regular expression, which will remove consecutive white space characters with non white space characters outside both ends (I'm not very good at using it yet, and there may be a better solution):
>>> import re
>>> re.sub(r'(?<=[^ ]) +(?=[^ ])', '', ' Swarnendu Pal is a good boy ')
' SwarnenduPalisagoodboy '

How to move a white space in a string?

I need to move a whitespace in a string one position to the right.
This is my code:
for i in range(0,len(resultaat)):
if resultaat[i] == " ":
string = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:]
E.g.:
If resultaat =
"TH EZE NO FPYTHON."
Than my output needs to be:
'THE ZEN OF PYTHON.'
, but the output that I get is:
"TH EZE NO F PYTHON."
I think this happened because the loop undid the action where it moved the previous space.
I don't know how to fix this problem.
Can someone help me with this?
Thanks!
Each time through the loop you're getting slices of the original resultaat string, without the changes you've made for previous iterations.
You should copy resultaat to string first, then use that as the source of each slice so you accumulate all the changes.
string = resultaat
for i in range(0,len(resultaat)):
if resultaat[i] == " ":
string = string[:i] + string[i+1] + " " + string[i+2:]
You could do something like this:
# first get the indexes that the character you want to merge
indexes = [i for i, c in enumerate(resultaat) if c == ' ']
for i in indexes: # go through those indexes and swap the characters as you have done
resultaat = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:] # updating resultaat each time you want to swap characters
Assuming the stated input value actually has one more space than is actually needed then:
TXT = "TH EZE NO FPYTHON."
def process(s):
t = list(s)
for i, c in enumerate(t[:-1]):
if c == ' ':
t[i+1], t[i] = ' ', t[i+1]
return ''.join(t)
print(process(TXT))
Output:
THE ZEN OF PYTHON.

How to find start and end of a string

Intention is to write a function that would reverse the words in a string. So that if the input is: "I am a student" the output should be "student am a I"
I have the following code in Python which first reverses all the characters in a string and then loops the reversed sentence to reverse the words and prints them to a "final sentence" variable.
Because the condition I am checking for is just a space, the first word doesn't get printed i.e. if the input is " I am a student" my code works (notice the space before "I") ... however if the input is "I am a student" then the output is just "student a am"
I need to know how can I modify my IF statement so it doesn't miss the first word
def reverse(sentence):
count = 0
new_sentence = ''
final_sentence = ''
counter = 0
word = ''
for char in sentence[::-1]:
new_sentence = new_sentence + char
for char in new_sentence:
if char != " ":
count = count + 1
continue
else:
for i in new_sentence[count-1::-1]:
if i != " ":
word = word + i
else:
break
count = count + 1
final_sentence = final_sentence + " " + word
word = ''
print final_sentence
reverse("I am a student")
I'm not sure why you are doing such complicated loops? You can just split the sentence, reverse and then join it again:
>>> ' '.join('I am a student'.split(' ')[::-1])
'student a am I'
To translate that into a function:
def reverse_sentence(sentence):
return ' '.join(sentence.split(' ')[::-1])
You're doing several strange things in your code. For example:
new_sentence = ''
for char in sentence[::-1]:
new_sentence = new_sentence + char
The string you're building through concatenation is already present in sentence[::-1]. You could've just done new_sentence = sentence[::-1].
You can check for the first word by using enumerate() and checking whether there is a space prior to that point in the sentence:
for idx,char in enumerate(new_sentence):
if char != " " or ' ' not in new_sentence[:idx]:
However, the easiest way to accomplish your actual goal is with split(), splitting the sentence by whitespace automatically. Use join() to put it back together once you've reversed it.
def reverse(sentence):
return ' '.join(sentence.split()[::-1])

Lists and Strings PYTHON - beginner

I am having issues with formatting and understand lists and strings when it comes to classes.
So I have this code here:
class User:
def __init__(self,title):
self.tile=tile
self.rank={}
def addCard(self,compID,number):
if compID in self.cards and number > self.cards[compID]:
self.cards[compID]=number
elif compID not in self.cards:
self.cards[compID]=number
def __str__(self):
self.cardList = []
for compID, number in self.cards.items():
final = compID + "-" + str(number)
self.cardList.append(temp)
self.cardList.sort()
return self.tile + ":" + " " + "Card scores:" + str(self.cardList)
so my result looks like this:
OUTPUT 1:
Cpt.Fred: Card scores: ['diamond-22', 'hearts-4', 'spades-3']
Lt.Connor: Card scores: ['diamond-43']
I am trying to make my result look like this:
OUTPUT 2:
Cpt.Fred: Card scores: [ diamond-22, hearts-4, spades-3 ]
Lt.Connor: Card scores: [ diamond-43 ]
The data is not whats important, its how to get rid of the " ' " at the beginning and the end of the results. I think it has something to do with my last def() statement but I have been trying to format it every way with no luck. Can anyone help turn the first output to look like the second output?
Instead of calling str(self.cardList), you should do:
return "%s: Card scores: [%s]" % (self.title, ", ".join(self.cardList))
The problem is that str on a list calls repr (includes quotes) on the list's elements, whereas you just want the str of the elements joined by commas.
You may need to process and print the list manually. Here's one way you could do that.
def printList(cardlist):
printstr = "[" # Start with [.
for card in cardlist:
printstr += card + ", " "card, "
printstr = printstr[:-2] + "]" # Remove the last ", " before adding the last ].
The problem is in "str(self.cardList)". It prints out the list as is, meaning it puts strings into quotations to distinguished them from numbers and other objects.
def list_to_string(some_list):
str = "["
for i in range(len(some_list)):
str += some_list[i]
if i < len(some_list)-1:
str += ", "
str += "]"
return str
this would parse your list into a string without the quotations

Python: turning a tuple from return statement into a string

I've been working on HTTLCS and am having some difficulty finishing up the problem.
Solving a problem was not much of an issue, but I have trouble returning my result as a string rather than the tuple data type.
Here is my code:
def wordCount(paragraph):
splited = paragraph.split()
wordnum = len(splited)
eWord = []
for aWord in splited:
if "e" in aWord:
eWord.append(aWord)
eWordnum = len(eWord)
percent = round(eWordnum / wordnum * 100,2)
return "Your text contains", wordnum, "words, of which" , eWordnum , "(" , percent , "%)" , "contains an 'e'."
print(wordCount(p))
Python outputs ('Your text contains', 108, 'words, of which', 50, '(', 46.3, '%)', "contains an 'e'.") which is a tuple, not a string.
I know I can just put print at the end of the function and call the function without print() statement, but how do I solve this with a return statement?
It's because you're using commas in your return statement, which Python is interpreting as a tuple. Try using format() instead:
def wordCount(paragraph):
splited = paragraph.split()
wordnum = len(splited)
eWord = []
for aWord in splited:
if "e" in aWord:
eWord.append(aWord)
eWordnum = len(eWord)
percent = round(eWordnum / wordnum * 100,2)
return "Your text contains {0} words, of which {1} ({2}%) contains an 'e'".format(wordnum, eWordnum, percent)
>>> wordCount("doodle bugs")
"Your text contains 2 words, of which 1 (0.0%) contains an 'e'"
return "Your text contains {0} words, of which {1} ({2}%) contains an 'e'.".format(wordnum,eWordnum,percent)
return "Your text contains " + str(wordnum) +
" words, of which " + str(eWordnum) +
" (" + str(percent) + "%)" + " contains an 'e'."
or
return "Your text contains %s words, of which %s (%s%%) contains an 'e'."
% (wordnum, eWordnum, percent)
In the first case, you do a string concatenation and you have to convert wordnum, eWordnum and other variables that are numeric ones, into str (by doing str(variableName)) to allow the concatenation (and for haven't runtime error)
In the second case, you do a string replacement that means that you give some kind of "placeholder" %s (that means string) and you replace them with tuple argument that follows the % symbol
If you return something separate by , you'll return a tuple (as you can see)
return "Your text contains %s words, of which %s (%s%%) contains an 'e'." % (wordnum, eWordnum, percent)
A for loop might work, though you would have to format the strings to add spaces to them.
for item in tuplename: print item,
Make sure to keep the comma after item, because that prints it on the same line.
def wordCount(paragraph):
splited = paragraph.split()
wordnum = len(splited)
eWord = []
for aWord in splited:
if "e" in aWord:
eWord.append(aWord)
eWordnum = len(eWord)
percent = round(eWordnum / wordnum * 100,2)
dummy = "Your text contains {0} words, of which {1} {2} contains an 'e'.".format(wordnum,eWordnum, percent)
return dummy
print(wordCount(p))
try this :
return "Your text contains %(wordnum)s words, of which %(ewordnum)s (%(percent)s %%), contains an 'e'."%locals()
using %(variable_name)s as string formatting is often easier to maintain.
how about this
return "Your text contains " + wordnum + " words, of which " + eWordnum + " (" + percent + "%) " + " contains an 'e'."
replace the commas with "+", this should work.

Categories

Resources