Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Here is my function:
def find_last(str1):
return str1[-1]
When i run it:
print find_last('aaaa')
I have the following error:
return str1[-1]
IndexError: string index out of range
How can I fix this?
Thanks.
The function as you have written it fails only if an empty string is passed in (or something that's not a string or other sequence, of course). A great way to make sure this works without having to check for the empty string is to use slicing rather than indexing:
def get_last(text):
return text[-1:]
This means "return from the last character through the end." This works even on empty strings because slicing stops at either end of the string automatically.
Your code is fine:
>>> def find_last(str1):
... return str1[-1]
...
>>> print find_last('aaaa')
a
>>>
You shouldn't get that response with 'aaaa' but you could improve your function with:
def find_last(str1):
return str1[-1] if str1 else None
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Currently I am learning Python from the book 'The Coders Apprentice' and I have stumbled upon an exercise which I have the feeling that I have nearly solved, but I get an error when I execute the program.
This is the exercise:
Write a program that takes a string and produces a new string that contains the exact characters that the first string contains, but in order of their ASCII-codes.
For instance, the string "Hello, world!" should be turned into " !,Hdellloorw". This is
relatively easy to do with list functions, which will be introduced in a future chapter, but for now try to do it with string manipulation functions alone.
I have added the code below and the error message as a picture.
from pcinput import getString
entString=getString("Enter your string here: ")
yourString=entString.strip()
def positioner(oldPosition):
newPosition=0
x=0
while x<len(yourString):
if ord(yourString[oldPosition])>ord(yourString[x]):
newPosition+=1
x+=1
return newPosition
i=0
y=0
newString=""
while y<len(yourString):
if positioner(i)==y:
newString+=yourString[i]
y+=1
elif positioner(i)<y:
newString+=yourString[i]
if i<len(yourString):
i+=1
else:
i=0
print(newString)
What have I done wrong? I am new to programming.
You are getting an index error because the line if positioner(i)==y: is being called with a value of i equal to the length of yourString. yourString[oldPosition] is then accessing an index which doesn't exist.
This is happening because the loop condition (y<len(yourString)) isn't doing any checking on the value of i, which is the one causing problems.
Some other quick comments:
You can use yourString = input("Enter your string here: ") to replace the first four lines, as I'm not sure what pcinput is - and couldn't find any packages of the same name.
Instead of using the while/x+=1 construct, you could instead use a for x in range(len(yourString)), which is a little neater.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Following is the code to check if a list of items is in arithmetic progression or not.
def ap():
l=[int(x) for x in list(input("Enter the list: "))]
diff=l[1]-l[0]
for i in range(len(l)-1):
if not ( l[i+1]-l[i]==diff):
return False
return True
When I am executing the above code, it is working fine, but If I am modifying the code and don't use the "not" keyword it is returning true in all the cases.
Following is the code:
def ap():
l=[int(x) for x in list(input("Enter the list: "))]
diff=l[1]-l[0]
for i in range(len(l)-1):
if (l[i+1]-l[i]==diff):
return True
return False
Can someone please help me to figure out where am I going wrong?
Of course it does. You get the difference between the first two elements, and then in your loop, the first step will check if the difference between the first two elements is the same, which it will always be. So, it will always return true in the first iteration of the loop.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have this so far:
def char_count(string, search):
newList = list(string)
return newList.count(search)
When I run it, I get:
TypeError: list() takes 0 positional arguments but 1 was given
This is bizarre to me because I thought the list function DOES take a parameter?
What's wrong with my code?
Thanks
The list constructor can indeed take one positional argument (an iterable like a string). I guess, you shadowed the name 'list' somewhere in your code. You should avoid naming your variables like built-ins (int, list, etc.) or commonly used modules (e.g. string).
Why don't you use the string's count() method anyway:
return string.count(search)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So here's my Python code:
my_name = "Hello<split>my<split>name<split>is<split>Max"
print my_name
Results would be:
Hello<split>my<split>name<split>is<split>Max
But I would like the results to look like this instead:
Hello
my
name
is
Max
The tag "split" was removed and a new line was created.
Any ideas on how to about doing that in Python?
Looks like a job for str.split():
>>> my_name = "Hello<split>my<split>name<split>is<split>Max"
>>>
>>> for s in my_name.split('<split>'):
... print s
...
Hello
my
name
is
Max
If you want the result as a single string you can use str.replace() as others have mentioned:
>>> import os
>>> my_name.replace('<split>', os.linesep)
'Hello\nmy\nname\nis\nMax'
Or you can rejoin the split:
>>> os.linesep.join(my_name.split('<split>'))
'Hello\nmy\nname\nis\nMax'
Though I would prefer the replacing method.
Sure
print my_name.replace("<split>","\n")
displays
Hello
my
name
is
Max
print my_name.replace("<split>", "\n")
You can split a string using the built in function split Here is an example that uses a generator object to append a new line to every substring:
my_name_split = [s + '\n' for s in my_name.split("<split>")]
alternatively, if you just want to print the split string without actually creating a new variable, you can simply replace "<split>" with "\n" using replace:
print my_name.replace("<split>","\n")
Note that this does not actually change the value of my_name.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Can someone please explain this program, I don't understand where role, line-spoken come from
>>> data = open('sketch.txt')
>>> for each_line in data: // stores each line from the sketch file in each_line
... (role, line_spoken) = each_line.split(':')
... print(role, end='')
... print(' said: ', end='')
... print(line_spoken, end='')
You are looking at a tuple assignment.
The right-hand side expression is expected to have resulted in a sequence of two elements, and these two elements are assigned to the two named targets on the left hand side.
In other words, .split(:) is expected to return two values, and those two values are assigned to the variables role and line_spoken. Most likely, the lines in the file contain text like hamlet:To be or not to be, that is the question\n.
If each_line.split(':') does not return two values, an exception will be raised instead.
role and line_spoken are variables, which are populated with strings read from the file sketch.txt. sketch.txt contains colon-separated pairs of words or phrases, and role and line_spoken get those words/phrases.
The split() function returns a "tuple", which is "unpacked" into your two variables.
(Note that the parentheses around (role, line_spoken) are unnecessary.)