Tiger1
Tiger1

Reputation: 1377

How to trim a string: begin immediately after the first full-stop and end at the last

Is there a way to trim a string to begin and end at specific points?

Here's an example: I would like the string (text) to begin immediately after the first full-stop and end at the last full-stop.

_string = "money is good. love is better. be lucky to have any. can't really have both"

Expected output:

"love is better. be lucky to have any."

My attempt:

import re
pattern = "\.(?P<_string>.*?.*?).\"
match = re.search(pattern, _string)
if match != None:
    print match.group("_string")

My attempt started well but stopped at the second full_stop.

Any ideas on how to arrive at the expected output?

Upvotes: 5

Views: 1658

Answers (4)

Scorpion_God
Scorpion_God

Reputation: 1499

What about using the .index() and .rindex() methods with string slicing?

string = "money is good. love is better. be lucky to have any. can't really have both"
first_full_stop = string.index('.')
last_full_stop = string.rindex('.')
string = string[first_full_stop+1:last_full_stop+1]

Or you can split by full stops (this one works with any number of full stops):

string = "money is good. love is better. be lucky to have any. can't really have both"
string = string.split('.')
string = string[1:-1]

Upvotes: 1

Nandha Kumar
Nandha Kumar

Reputation: 385

import re
_string = "money is good. love is better. be lucky to have any. can't really have both"
str1 =_string[_string.find(".")+1:]
for i in range(len(str1)-1,0,-1):
if(str1[i]=='.'):
    a=str1[:i+1]
    break
print a
#love is better. be lucky to have any.

Upvotes: 0

Ammar
Ammar

Reputation: 1324

The regex should be:

 \.(.*\.)

this will catch all the text except newline between the first and last .

explanation:

\. matches the character . literally
1st Capturing group (.*\.)
    .* matches any character (except newline)
        Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
    \. matches the character . literally

if you do not want the space at the beginning just use this one:

\.\s(.*\.)

hope this helps.

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239473

This will work, if there is atleast one dot in the string.

print _string[_string.index(".") + 1:_string.rindex(".") + 1]
#  love is better. be lucky to have any.

If you don't want the space at the beginning, then you strip that like this

print _string[_string.index(".") + 1:_string.rindex(".") + 1].lstrip()
# love is better. be lucky to have any.

Upvotes: 5

Related Questions