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?
The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.
strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
Use the lastIndexOf() method to get the substring before the last occurrence of a specific character, e.g. str. substring(0, str. lastIndexOf('_')); . The substring method will return a new string containing the part of the string before the last occurrence of the specified character.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With