I have a string
st = 'A Interface'
. I want to extract part of the string before the 1st white space. I want it to be,st = 'A'
. I can do this via slicing of the string because I know the index of the 1st white space but how can I do it if I don't know the index?
Asked
Active
Viewed 2,090 times
0

Rabi Siddique
- 49
- 6
1 Answers
6
You could use split()
:
st = 'A Interface'
first = st.split()[0]
This solution is even robust to be there being more than one space after the first word character(s). In event that you might not know which type of whitespace character could be the separator, and for a more general solution, you could use re.findall
:
st = 'A Interface'
first = re.findall(r'^\S', st)[0]

Tim Biegeleisen
- 502,043
- 27
- 286
- 360