Just use the split function. It returns a list, so you can keep the first element:
>>> s1.split(':')
['Username', ' How are you today?']
>>> s1.split(':')[0]
'Username'
Answer from fredtantini on Stack OverflowJust use the split function. It returns a list, so you can keep the first element:
>>> s1.split(':')
['Username', ' How are you today?']
>>> s1.split(':')[0]
'Username'
Using index:
>>> string = "Username: How are you today?"
>>> string[:string.index(":")]
'Username'
The index will give you the position of : in string, then you can slice it.
If you want to use regex:
>>> import re
>>> re.match("(.*?):",string).group()
'Username'
match matches from the start of the string.
you can also use itertools.takewhile
>>> import itertools
>>> "".join(itertools.takewhile(lambda x: x!=":", string))
'Username'
regex - Python search / extract string before and after a character - Stack Overflow
python - Extract the word before a specific character - Stack Overflow
python - how to get the last part of a string before a certain character? - Stack Overflow
python - Extract string before specific character - Stack Overflow
You don't need a regex here, just use str.partition(), splitting on the | plus the surrounding spaces:
string1, separator, string2 = string.partition(' | ')
Demo:
>>> string = "My City | August 5"
>>> string.partition(' | ')
('My City', ' | ', 'August 5')
>>> string1, separator, string2 = string.partition(' | ')
>>> string1
'My City'
>>> string2
'August 5'
str.partition() splits the string just once; if there are more | characters those are left as part of string2.
If you want to make it a little more robust and handle any number of spaces around the pipe symbol, you can split on just | and use str.strip() to remove arbitrary amounts of whitespace from the start and end of the two strings:
string1, separator, string2 = map(str.strip, string.partition('|'))
You don't need regular expressions here. Just type
string = "My City | August 5"
string1, string2 = string.split("|")
If you want to crop the trailing space in the results, you can use
string1 = string1.strip(" ")
string2 = string2.strip(" ")
You are looking for str.rsplit(), with a limit:
print x.rsplit('-', 1)[0]
.rsplit() searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.
Another option is to use str.rpartition(), which will only ever split just once:
print x.rpartition('-')[0]
For splitting just once, str.rpartition() is the faster method as well; if you need to split more than once you can only use str.rsplit().
Demo:
>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'
and the same with str.rpartition()
>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'
Difference between split and partition is split returns the list without delimiter and will split where ever it gets delimiter in string i.e.
x = 'http://test.com/lalala-134-431'
a,b,c = x.split(-)
print(a)
"http://test.com/lalala"
print(b)
"134"
print(c)
"431"
and partition will divide the string with only first delimiter and will only return 3 values in list
x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala"
print(b)
"-"
print(c)
"134-431"
so as you want last value you can use rpartition it works in same way but it will find delimiter from end of string
x = 'http://test.com/lalala-134-431'
a,b,c = x.rpartition('-')
print(a)
"http://test.com/lalala-134"
print(b)
"-"
print(c)
"431"
would this work:
name ='Egyptian_Mau_214.jpg'
m = re.split(r'_(?=\d+\.[a-z]+$)', name)
print(m) # ['Egyptian_Mau', '214.jpg']
Hope I got it right, but you could use a regex. For your example:
import re
r = re.compile('(.+)_(\d+\.jpg)')
m = r.match('Egyptian_Mau_214.jpg')
print(m.groups()) # -> ('Egyptian_Mau', '214.jpg')
Regex explanation:
(.+)- Group 1, 1 or more of any character._- Just an underscore.(\d+\.jpg)- Group 2, one or more digits, and.jpgsuffix.
I am not really sure if this is what you want, but it does the work:
regions = []
for i in df['Region'].str.split('.').str[0]:
regions.append(''.join([d for d in i if d.isdigit()]))
df['BGC Region'] = df['Strain'].str.split('_').str[2] + '_' + regions + '.region'
region_number = df['Region'].str.split('.').str[1]
for i, rn in enumerate(region_number):
if int(rn) < 10:
df['BGC Region'][i] += '00' + rn
elif int(rn) < 100:
df['BGC Region'][i] += '0' + rn
The idea is to:
- concatenate your 2 columns (inserting a '_' between them),
- call
str.extractto extract the parts of interest, specified with a regex pattern with proper named capturing groups, - for each row, merge these parts, adding the required number of zeroes.
To implement it, start with creating of an intermediate DataFrame:
df2 = (df.Strain + '_' + df.Region).str.extract(
r'(?:[^_]+_){2}(?P<QL>[^_]+)_[^_]+_(?P<Rg>[^&]+)\D+(?P<D1>\d)\.(?P<D2>\d)')
The result, for your data, is:
QL Rg D1 D2
0 QL40 Region 1 1
1 QL40 Region 2 2
2 QL40 Region 2 1
Then define a merging function, to be applied for each row from df2:
def mrg(row):
rg = row.Rg + '0'
if len(rg) < 11:
rg += '0'
return row.QL + '_' + row.D1 + '.' + rg + row.D2
And to get the final result, run:
region_list = df2.apply(mrg, axis=1).tolist()
The result is:
['QL40_1.Region001', 'QL40_2.Region002', 'QL40_2.Region001']