Reputation: 21
Example, I have a field of names like 'Smith Joe' and I need a python statement to select 'Smith J'. I can get everything up to the space using the following:
x = 'Smith Joe'
x[:x.rindex(' ')]
'Smith'
Upvotes: 2
Views: 224
Reputation: 142216
I might be tempted to do something like:
import re
x = 'Smith Joe'
print re.match('\w+\s\w', x).group()
# Smith J
This'll enable easier tweaking for grouping and formatting, eg:
m = re.match('(\w+)\s(\w)', x)
print 'Mr. {1} {0}'.format(*m.groups())
Upvotes: 2
Reputation: 122208
x = 'Smith Joe'.split()
y = x[0] + " "+ x[1][0]
a = 'Smith Joe King Cole'.split()
b = x[0]+" "+" ".join([t[0] for t in x[1:])
Upvotes: 0
Reputation: 1131
Couldn't you just increment the :x.rindex(' ') by 2, which would include the first character after the space?
x[:x.rindex(' ') + 2]
Upvotes: 2