How to move a white space in a string? - python

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.

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 '

Remove extra space before word ends

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")

Removing And Re-Inserting Spaces

What is the most efficient way to remove spaces from a text, and then after the neccessary function has been performed, re-insert the previously removed spacing?
Take this example below, here is a program for encoding a simple railfence cipher:
from string import ascii_lowercase
string = "Hello World Today"
string = string.replace(" ", "").lower()
print(string[::2] + string[1::2])
This outputs the following:
hlooltdyelwrdoa
This is because it must remove the spacing prior to encoding the text. However, if I now want to re-insert the spacing to make it:
hlool tdyel wrdoa
What is the most efficient way of doing this?
As mentioned by one of the other commenters, you need to record where the spaces came from then add them back in
from string import ascii_lowercase
string = "Hello World Today"
# Get list of spaces
spaces = [i for i,x in enumerate(string) if x == ' ']
string = string.replace(" ", "").lower()
# Set string with ciphered text
ciphered = (string[::2] + string[1::2])
# Reinsert spaces
for space in spaces:
ciphered = ciphered[:space] + ' ' + ciphered[space:]
print(ciphered)
You could use str.split to help you out. When you split on spaces, the lengths of the remaining segments will tell you where to split the processed string:
broken = string.split(' ')
sizes = list(map(len, broken))
You'll need the cumulative sum of the sizes:
from itertools import accumulate, chain
cs = accumulate(sizes)
Now you can reinstate the spaces:
processed = ''.join(broken).lower()
processed = processed[::2] + processed[1::2]
chunks = [processed[index:size] for index, size in zip(chain([0], cs), sizes)]
result = ' '.join(chunks)
This solution is not especially straightforward or efficient, but it does avoid explicit loops.
Using list and join operation,
random_string = "Hello World Today"
space_position = [pos for pos, char in enumerate(random_string) if char == ' ']
random_string = random_string.replace(" ", "").lower()
random_string = list(random_string[::2] + random_string[1::2])
for index in space_position:
random_string.insert(index, ' ')
random_string = ''.join(random_string)
print(random_string)
I think this might Help
string = "Hello World Today"
nonSpaceyString = string.replace(" ", "").lower()
randomString = nonSpaceyString[::2] + nonSpaceyString[1::2]
spaceSet = [i for i, x in enumerate(string) if x == " "]
for index in spaceSet:
randomString = randomString[:index] + " " + randomString[index:]
print(randomString)
string = "Hello World Today"
# getting index of ' '
index = [i for i in range(len(string)) if string[i]==' ']
# storing the non ' ' characters
data = [i for i in string.lower() if i!=' ']
# applying cipher code as mention in OP STATEMENT
result = data[::2]+data[1::2]
# inserting back the spaces in there position as they had in original string
for i in index:
result.insert(i, ' ')
# creating a string solution
solution = ''.join(result)
print(solution)
# output hlool tdyel wrdoa
You can make a new string with this small yet simple (kind of) code:
Note this doesn't use any libraries, which might make this slower, but less confusing.
def weird_string(string): # get input value
spaceless = ''.join([c for c in string if c != ' ']) # get spaceless version
skipped = spaceless[::2] + spaceless[1::2] # get new unique 'code'
result = list(skipped) # get list of one letter strings
for i in range(len(string)): # loop over strings
if string[i] == ' ': # if a space 'was' here
result.insert(i, ' ') # add the space back
# end for
s = ''.join(result) # join the results back
return s # return the result

Python value assignment does not print

I'm a student and have a question. I'm not getting the correct output in our textbook.
first = 'I'
second = 'love'
third = 'Python'
sentence = first + '' + second + '' + third + '.'
Output:
I love Python.
When I run it, nothing happens. Can someone explain why? Thanks in advance!
print sentence. Will print the outut
But from what you have this will output "IlovePython." not I love Python.
This is because ther is no space between your '' tags. To fix this convert all those '' to ' '. Save the last one, which is . as it should be.
Your sentence variable should be:
sentence = first + ' ' + second + ' ' + third + '.'
and after assigning the value to sentence you have to print it:
print (sentence)
Also you can print directly the concatenation without saving it into a variable:
print (first + ' ' + second + ' ' + third + '.')

How do I remove spaces in a string using a loop in python?

def onlyLetters(s):
for i in range(len(s)):
if s[i] == " ":
s = s[:i] + s[i+1:]
return s
return s
Why is my above loop not working? It seems like it's only doing it once.
For example, if i have the string "Hello how are you", it's returning "Hellohow are you". I want it to check the string again and remove another space, and keep doing it until there are no spaces left. How do I fix this code?
Your code is stopping after the first space is replaced because you've told it to. You have return s inside the loop, and when that is reached, the rest of the loop is abandoned since the function exits. You should remove that line entirely.
There's another issue though, related to how you're indexing. When you iterate on range(len(s)) for your indexes, you're going to go to the length of the original string. If you've removed some spaces, however, those last few indexes will no longer be valid (since the modified string is shorter). Another similar issue will come up if there are two spaces in a row (as in "foo bar"). Your code will only be able to replace the first one. After the first space is removed, the second spaces will move up and be at the same index, but the loop will move on to the next index without seeing it.
You can fix this in two different ways. The easiest fix is to loop over the indexes in reverse order. Removing a space towards the end won't change the indexes of the earlier spaces, and the numerically smallest indexes will always be valid even as the string shrinks.
def onlyLetters(s):
for i in range(len(s)-1, -1, -1): # loop in reverse order
if s[i] == " ":
s = s[:i] + s[i+1:]
return s
The other approach is to abandon the for loop for the indexes and use a while loop while manually updating the index variable:
def onlyLetters(s):
i = 0
while i < len(s):
if s[i] == " ":
s = s[:i] + s[i+1:]
else:
i += 1
return s
If you want to remove all spaces, use str.replace():
sentence = ' Freeman was here'
sentence.replace(" ", "")
>>> 'Freemanwashere'
If you want to remove leading and ending spaces, use str.strip():
sentence = ' Freeman was here'
sentence.strip()
>>> 'Freeman was here'
If you want to remove duplicated spaces, use str.split():
sentence = ' Freeman was here'
" ".join(sentence.split())
>>> 'Freemanwashere'
If you also want to remove all the other strange whitespace characters that exist in unicode you can use re.sub with the re.UNICODE arguement:
text = re.sub(r"\s+", "", text, flags=re.UNICODE)
or something like this,it's handles any whitespace characters that you're not thinking of 😉 :
>>> import re
>>> re.sub(r'\s+', '', 'Freeman was here')
'Freemanwashere'
if you don’t want to use anything like replace() or join() etc. you can do this :
def filter(input):
for i in input:
yield " " if i in " ,.?!;:" else i
def expand(input):
for i in input:
yield None if i == " " else object(), i
def uniq(input):
last = object()
for key, i in input:
if key == last:
continue
yield key, i
def compact(input):
for key, i in input:
yield i
yourText = compact(uniq(expand(filter(input()))))
just use python replace() method for Strings.
s.replace(" ","")
It's a little hard to tell, because the indentation in your example is hard to understand. But it looks to me like after you encounter and remove the very first space, you are returning s. So you only get a chance to remove one space before returning.
Try only returning s once you are out of the for loop.
You can do s.replace(" ", ""). This will take all your spaces (" ") and replace it by nothing (""), effectively removing the spaces.
You're returning the function after the first occurrence of a ",", which means it exits the loop and the function altogether. That's why it's only working for the first comma.
Try this,
def onlyLetters(s):
length=len(s)
i=0
while(i<length):
if s[i] == " ":
s = s[:i] + s[i+1:]
length=len(s)
else
i+=1
return s
If you want to use your own code only then try running this:
def onlyLetters(s):
for i in range(len(s)):
if s[i] == " ":
s = s[:i] + s[i+1:]
return s
or better you may use:
def onlyLetters(s):
return s.replace(" ","")
def remove_spaces(text):
text_with_out_spaces='';
while text!='':
next_character=text[0];
if next_character!=' ':
text_with_out_spaces=text_with_out_spaces +next_character;
text=text[1:];
return text_with_out_spaces
print remove_spaces("Hi Azzam !! ?");

Categories

Resources