I know that it is very weird code, but try not to pay attention. I just want to solve this task with such a strange method. But in the process, I am faced with this problem. Can you help me to fix it?
in <module>
in reverse_alternate
IndexError: string index out of range
I suppose that it's associated with modulo. Right?
def reverse_alternate(string):
a = string.split(' ')
new = ''
for i, c in enumerate(a):
if i % 2 != 0:
new += ' ' + c[::-1] + ' '
else:
new += c
if new[-1] == ' ':
a = new[:-1]
return a
else:
return new
Replace
if new[-1] == ' ':
with
if len(new) and new[-1] == ' ':
If you have no tokens, new will end up being empty, and as such, it won't have the -1'st element. Thus, referencing it would result in "index out of range" error.
Related
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.
I am parsing a string for spaces and i find that the string index is not getting updated even after updating the string, where am i wrong ? will be very happy for any guidance provided
class Palindrome:
def __init__(self,seq):
self.seq=seq.lower()
def remove_space(self):
print('up',self.seq)
for num,i in enumerate(self.seq):
print('start',self.seq)
if i==' ':
print('orig',(num,i))
new_seq=self.seq[:num]+self.seq[num+1:]
num=num+1
self.seq=new_seq # updating the string here
print('now',self.seq)
print(num)
#print(new_seq)
seq1=Palindrome('superman is here')
seq1.remove_space() ```
If you want to proceed with your method, you need to account for the number of spaces you've already removed from the string. And I also included an alternative way of removing space while still using a loop.
class Palindrome:
def __init__(self,seq):
self.seq=seq.lower()
def remove_space_alt(self):
print(self.seq)
temp_string = ''
for i, letter in enumerate(self.seq):
if letter != ' ':
temp_string += letter
self.seq = temp_string
print(self.seq)
def remove_space(self):
print(self.seq)
space_count = 0
for i, letter in enumerate(self.seq):
if letter == ' ':
first = self.seq[:i - space_count]
second = self.seq[i + 1 - space_count:]
space_count += 1
self.seq = first + second
print(self.seq)
print('Showing remove_space')
seq1=Palindrome('superman is here')
seq1.remove_space()
print('\nShowing remove_space_alt')
seq1=Palindrome('superman is here')
seq1.remove_space_alt()
Output:
Showing remove_space
superman is here
supermanis here
supermanishere
Showing remove_space_alt
superman is here
supermanishere
Original Post: Suggested using string replace() to remove spaces, and did not fully explain issue with changing for-loop index mid loop.
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 + '.')
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
I am pretty new to Python and I am having trouble with this 'quiz' I am creating.
answer_1_choices = {
'A' : 'A: A list is a datatype that stores a sequence of items with individual indexes that are mutable.',
'B' : 'B: A list is a datatype that stores a sequence of items with individual indexes that are immutable.',
'C' : 'C: A list is a datatype that stores a sequence of items assigned to individual keys that are immutable.'
}
Number_One = '1. What is a list?'
def answer():
x = input()
if x == 'A' or x == 'a':
print('Correct!')
else:
print('That is an incorrect response. Please try again.' + '\n' + '\n' + Number_One + '\n')
print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' + answer_1_choices['C'])
print('\n' + 'Is the answer A, B, or C? Type the letter of your choice.')
def question_one():
print(Number_One + '\n')
print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' + answer_1_choices['C'])
print('\n' + 'Is the answer A, B, or C? Type the letter of your choice.')
question_one()
answer()
I want the else statement to run infinitely every time that the input is something other than 'A' or 'a'. I know I have to use some kind of loop or something, but I just can't seem to figure it out. Can someone help me?
What you're thinking of there is a while loop. Instead of checking for x = 'A' or x = 'a', you might try testing for whether x isn't 'A' or 'a'.
Try this:
while (x != 'A' and x != 'a'):
print('That is an incorrect response. Please try again.' + '\n' + '\n' + Number_One + '\n')
print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' + answer_1_choices['C'])
x = input('\n' + 'Is the answer A, B, or C? Type the letter of your choice.')
print('Correct!')
This way, it will only print "Correct!" once the breaking condition has been satisfied.
Add as the last line of the else case a recursive call:
answer()
Full code:
def answer():
x = input()
if x == 'A' or x == 'a':
print('Correct!')
else:
print('That is an incorrect response. Please try again.' + '\n' + '\n' + Number_One + '\n')
print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' + answer_1_choices['C'])
print('\n' + 'Is the answer A, B, or C? Type the letter of your choice.')
answer()
def insertNewLine(text, lenght):
if len(text) < lenght:
return text
else:
print text[:lenght]
return (text[:lenght]+'\n'+ insertNewLine(text[lenght:],lenght))
but the problem is that word is dividing by my program .. that should not happen.. e.g.
=> Input :
"Random text to wrap again." and Lenght: 5
=> My Output:
Rando
m tex
t to
wrap
again
.
=> Expected Output:
Random
text
to wrap
again.
It looks like you need to wrap on whole words after a certain length, and ignoring spaces; I'd do something like this:
def wrap(text, length):
words = text.split()
lines = []
line = ''
for w in words:
if len(w) + len(line) > length:
lines.append(line)
line = ''
line = line + w + ' '
if w is words[-1]: lines.append(line)
return '\n'.join(lines)
This basically works by splitting the text into whole words, and then assembling lines of them up to your wrap length. That way you don't have to figure out if you're trying to break in the middle of a word. I didn't bother to check whether your length is shorter than your longest word, but that's a consideration as well.
def insertNewLine(text, lenght):
if len(text) < lenght:
return text
else:
print text[:lenght]
return (text[:lenght]+'\n'+ insertNewLine(text[lenght:],lenght))
"Random text to wrap again." and Lenght: 5
The problem is that you are saying with
'\n'
That you want a new line ever 5 characters. The word Random has 6 which is why it is being cut at Rando. Also remember that the spaces count as a character as well. So when your recursion goes through it is simply counting 5 characters and then inserting a new line every 5.
This is a posible solution to your problem, I use re python module to put \n characters in the right place.
import re
def insertNewLine(text, lenght):
return re.sub('((.*){' + str(lenght-1) + ',}?)\s', '\g<1>\n', text)
if __name__ == "__main__":
print insertNewLine("Random text to wrap again.", 5)
>>>python test.py
Random
text
to wrap
again.
def insertNewline(text, length):
'''
This function can only be applied to normal text.
'''
if len(text) <= length:
print(text)
return
elif text[length - 1] == ' ':
print(text[:length - 1])
return insertNewline(text[(length):], length)
elif text[length] == ' ':
print(text[:length])
return insertNewline(text[(length + 1):], length)
else:
i = 0
while text[length + i] != ' ' and text[length + i] != ',' and text[length + i] != '.':
i += 1
if text[length + i] == ' ':
print(text[:(length + i)])
return insertNewline(text[(length + i + 1):], length)
else:
print(text[:(length + i + 1)])
return insertNewline(text[(length + i + 2):], length)
This code works correctly with normal text, by which I mean simple English sentences with only ',' and '.' as punctuations, and after each punctuation there is only one space, just as normal essay writing. If you want to apply this code to more complete text, I think you can update this code by yourself.
I use "recursion" as you required in your question. I think this code should be helpful for you.
I'm not an expert in python, and still in the learning process. Hope you can get what you want from my answer.