user2592049
user2592049

Reputation: 21

Python select one character after space

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

Answers (6)

zhangyangyu
zhangyangyu

Reputation: 8610

 x = 'Smith Joe'
 x[:x.rindex(' ') + 2 ]
'Smith J'

Upvotes: 2

Jon Clements
Jon Clements

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

alvas
alvas

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

Michael Liu
Michael Liu

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

Viktor Mellgren
Viktor Mellgren

Reputation: 4506

x = 'Smith Joe'
x[:x.rindex(' ') + 2]

Upvotes: 2

nwalsh
nwalsh

Reputation: 471

x = 'Smith Joe'
x[:x.rindex(' ') + 2]

Which gives

Smith J

Upvotes: 2

Related Questions