Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
maxsplit question
#1
Greetings!
I'm confused about the maxsplit.
Here is an example.
s = 'BKM0001-01-XLPM034NMS'
print(f"*** {s} ***")
dd = s.split('-',2)[0]
print(dd)
I'm trying to get 'BKM0001-01' from the string. I thought I'm splitting the string on the second (-) delimiter and it would print only the [0] element of the split, that is 'BKM0001-01' and I wanted to use the 'XLPM034NMS' the element 1 for something else.
But it prints 'BKM0001', no the 'BKM0001-01'

Thank you.
Reply
#2
split() always splits on the delimters from left to right. What the maxsplit does is tell it when to stop looking for delimiters.

>>> "A-B-C-D".split("-")
['A', 'B', 'C', 'D']
>>> "A-B-C-D".split("-", 2)
['A', 'B', 'C-D']
>>> "A-B-C-D".split("-", 1)
['A', 'B-C-D']
>>> "A-B-C-D".split("-", 0)
['A-B-C-D']
Since you only have 2 delimiters, you could use rsplit() instead which splits right to left.
>>> "BKM0001-01-XLPM034NMS".rsplit("-", 1)[0]
'BKM0001-01'
or if you had a variable number, you could just split the first three, and rejoin the first 2.
>>> "-".join("BKM0001-01-XLPM034NMS".split("-", 2)[:2])
'BKM0001-01'
Reply
#3
Awesome!
Thank you! Smile
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020