This question already has answers here:
Why is this list slice treating 0 and 1 as the same in Python? [duplicate]
(2 answers)
Understanding slicing
(38 answers)
Closed 8 years ago.
Let me preface this by saying I'm new to Python, come from Ruby, and I don't have much specific knowledge about how Python works.
For one of my current projects, I'm creating a new feature in a computational chemistry Django application that reads in PDBs and then does calculations on them. After adding my code, I was getting an error that Python can't typecast a string as a float, and looked at the library that parses the PDBs.
I was quickly confused by how Python's slice notation works. For example:
str = 'Hello this is Josh'
str[0:2] #=> 'He'
str[2] #=> 'l'
What I thought calling str[0:2] would result it would be Hel, not He, since index 0 to 2 is 3 big.
Is there a reason that this happens this way, and why str[m:n] gives from m to n-1, not from m to n?
It's so that:
str[0:2] + str[2:4] == str[0:4]
And
str[0:len(str)] == str
In general, it's conventional for sets of numbers to be defined this way; inclusive of the first listed number, exclusive of the second.
Esdgar Dijkstra wrote up a fairly well known argument for both this convention, and the convention of starting array indices at 0.
Related
This question already has answers here:
Getting a map() to return a list in Python 3.x
(11 answers)
Closed 2 years ago.
I was trying to write a million digits of pi in an array with each digit as an individual element of the array. The values are loaded from a '.txt' file from my computer. I have seen a similar question here. Written by the help of this, my code is:
import numpy as np
data = np.loadtxt('pi.txt')
print(map(int, str(data)))
But the output is this:
<map object at 0x0000000005748EB8>
Process finished with exit code 0
What does it mean?
A few operations with Python version 3 become "lazy" and for example mapping now doesn't return a list of values but a generator that will compute the values when you iterate over it.
A simple solution is changing the code to
print(list(map(int, str(data))))
This is quite a big semantic change and of course the automatic 2->3 migration tool takes care of it... if you programmed in Python 2 for a while however is something that will keep biting you for quite some time.
I'm not sure about why this change was considered a good idea.
map in Python 3 will give you a generator, not a list, but in python 2 it will give a list.
The stack overflow link you have given refers to Python 2 where as you are writing code in python 3.
you can refer to these ideone links.
python 2 https://ideone.com/aAhvLD
python 3 https://ideone.com/MjA5nj
so if you want to print list you can do
print(list(map(int, str(data))))
This question already has answers here:
Why is it string.join(list) instead of list.join(string)?
(11 answers)
Closed 7 years ago.
I have some previous experience with C++ and just getting started up with Python. I read this text from Dive into Python :
In my experience, a general idea is, if you want to perform an operation on object 'O', you call a method on that object to do it.
Eg. If I have a list object, and I want to get summation of all elements, I would do something like :
listObject.getSumOfAllElements()
However, the call given in above book excerpt looks a little odd to me. To me this would make more sense :
return (["%s=%s" % (k, v) for k, v in params.items()]).join(";")
i.e. join all the elements of the list as a string, and here, use this parameter ';' as a delimiter.
Is this a design difference or just syntactically a little different than what I am thinking ?
Edit:
For completion, the book says this a little later :
Is this a design difference or just syntactically a little different than what I am thinking?
Yes, I think it is by design. The join function is intentionally generic, so that it can be used with any iterable (including iterator objects and generators). This avoids implementing join for list, tuple, set etc separately.
This question already has answers here:
Are there limits to using string.lstrip() in python? [duplicate]
(3 answers)
Closed 8 years ago.
So I have a super long string composed of integers and I am trying to extract and remove the first three numbers in the string, and I have been using the lstrip method (the idea is kinda like pop) but sometimes it would remove more than three.
x="49008410..."
x.lstrip(x[0:3])
"8410..."
I was hoping it would just remove 490 and return 08410 but it's being stubborn -_- .
Also I am running Python 2.7 on Windows... And don't ask why the integers are strings. If that bothers you, just replace them with letters. Same thing! LOL
Instead of remove the first 3 numbers, get all numbers behind the third position. You can do it using : operator.
x="49008410..."
x[3:]
>> "8410..."
This question already has answers here:
How to create a range of numbers with a given increment
(6 answers)
Closed 8 years ago.
Does anybody know whether Python can do the same thing as for i= 1:2:5 in Matlab? So i=1,3,5.
I know I can use other approaches to do this, but I want to know the equivalent form in Python.
try:
for i in xrange(1,6,2):
print i
This print:
1
3
5
Use xrange instead of range if you are using python 2.x because it is more efficient as it generates an iterable object, and not the whole list.
Use the range function:
for i in range(1, 6, 2):
print(i)
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
reverse a string in Python
I tried searching the python documentation for a certain slicing exapmle
lets say I have this string
a = "ABCD"
when I write:
a[::-1]
I get the reversed string
"DCBA"
I can't understand how exectaly it works. None of the examples I saw were with two colons. what does it mean? how does it work?
thank you!
The full syntax of a slicing is
a[start:stop:step]
The step value denotes by how much to increase the index when going from one element of the slice to the next one. A value of -1 consequently means "go backwards". If start and stop are omitted as in your example, the default is to use the whole string (or more generally, the whole sequence, as this also works for lists and tuples).