Timeline for answer to How do I get a substring of a string in Python? by Michał Leon
Current License: CC BY-SA 4.0
Post Revisions
14 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Jan 17, 2023 at 15:06 | comment | added | Leslie Krause | For me, length is far more relevant than ending index. I usually know how long the captured string is since it rarely changes, For example, if I'm parsing a date "DD-MMM-YYYY", it's far more intuitive for me to specify year as starting index = 8 and length = 4. Trying to mentally figure out that ending index is error prone. | |
| Aug 7, 2022 at 2:20 | comment | added | mattmc3 |
No. This is epically bad advice. Python supports negative indexing, so the math won't work here at all. Imagine start=-4 and length=8 and your string is the alphabet; your math gets you an empty string as a result because you are getting the string between w and e, instead of the correct result, wxyz.
|
|
| Jan 29, 2022 at 22:16 | comment | added | AndyB |
@PhilHibbs "Like every other substring function" is rather too strong a statement, since there are at least two other common ways to interpret substring arguments. One is (start, length) and the other is (start, end). Python's (start, end+1) is admittedly unusual, but fits well with the way other things in Python work.
|
|
| Oct 9, 2019 at 9:00 | comment | added | Gloweye | As someone who began with Python instead of [dirty word]-languages like PHP, I think Python is much more simple and intuitive with its string[beginning:end]. Length generally isn't relevant. | |
| Mar 12, 2019 at 22:47 | comment | added | victortv |
A (probably) more pythonic way to do that is s[beginning:][:length]
|
|
| Jan 10, 2019 at 13:34 | comment | added | PhilHibbs | And just for completeness, Java is like Python in that the String.substring() method takes start and one-past-end. This one just bit me hard, I had assumed it was length like every other substring function in the world. | |
| Jun 22, 2018 at 15:24 | history | edited | Peter Mortensen | CC BY-SA 4.0 |
Active reading.
|
| S Jun 27, 2014 at 14:37 | history | suggested | CommunityBot | CC BY-SA 3.0 |
the second index is the first position which is not contained in the result (one after the end).
|
| Jun 27, 2014 at 14:31 | review | Suggested edits | |||
| S Jun 27, 2014 at 14:37 | |||||
| May 29, 2013 at 13:58 | comment | added | Nicu Surdu | The beginners should learn the pythonic way when moving to python, not stick to other language habits | |
| S Feb 8, 2013 at 16:44 | history | suggested | Seanog | CC BY-SA 3.0 |
Error in code
|
| Feb 8, 2013 at 16:40 | review | Suggested edits | |||
| S Feb 8, 2013 at 16:44 | |||||
| Sep 26, 2012 at 21:36 | review | Late answers | |||
| Sep 27, 2012 at 12:35 | |||||
| Aug 4, 2012 at 11:43 | history | answered | Michał Leon | CC BY-SA 3.0 |