6

I have the following string:

a = "this.is.a.string"

I wish to delete everything after the 3rd '.' symbol so that it returns

trim(a)
>>> "this.is.a"

while a string without the 3rd '.' should return itself.

This answer (How to remove all characters after a specific character in python?) was the closest solution I could find, however I don't think split would help me this time.

Community
  • 1
  • 1
sachinruk
  • 9,571
  • 12
  • 55
  • 86

4 Answers4

14

.split() by the dot and then .join():

>>> ".".join(a.split(".")[:3])
'this.is.a'

You may also specify the maxsplit argument since you need only 3 "slices":

If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).

>>> ".".join(a.split(".", 3)[:-1])
'this.is.a'
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 1
    Yes, this is definitely a good use case for `maxsplit` to avoid unnecessary splitting if the string contains more than 2 dots. – PM 2Ring Jan 31 '16 at 06:53
  • 1
    With `maxsplit`, you can also use `[:-1]` as the slice, regardless of the value of `maxsplit`. – chepner Jan 31 '16 at 15:54
2

@alecxe's answer is sufficient, however, you ask

Delete rest of string after n-th occurrence

To do that, you can do

def removeAfterN(yourStr, nth, occurenceOf):
    return occurenceOf.join(yourStr.split(occurenceOf)[:nth])

Where yourStr is your string, nth is the occurrence (in your example, it would be 3), and occurenceOf would be . from your example.

>>> removeAfterN("this.is.a.string",3,".")
'this.is.a'
intboolstring
  • 6,891
  • 5
  • 30
  • 44
0

you can use simple regex here and sub:

import re

print re.sub(r'\.a.*$', '.a', a)

\.a means literally symbols .a

.*$ means everything till the end

Or simple replace:

a.replace('.string','')

More common solution with re might be:

print re.sub(r'(^[a-z]+\.[a-z]+)\..*$', '\g<1>', a)

We are grouping every part with . and slicing the 3rd one.

[a-z]+ - means more than one letter

\..*$ means everything from second . till the end

\g<1> means group reference to first group ()

more detailed explanation on regex syntax you can find here

midori
  • 4,807
  • 5
  • 34
  • 62
  • could you explain what the re expressions do? – sachinruk Jan 31 '16 at 03:54
  • added some explanation – midori Jan 31 '16 at 03:58
  • I'm afraid all this does is get rid of the ".string" at the end. Try `a="this.is.all.of.a.a.string"' for example and you will see that only ".string" disappears with the last regex. I need all of string after 3rd period deleted (period symbol included) – sachinruk Jan 31 '16 at 04:20
-1
def trim(s):
    count = 0
    for i in range(len(s)):
        if s[i] == '.'
             if count == 2
                  s = s[:i]
                  break
             count += 1
ghui
  • 156
  • 3
  • 12