-1

I have a string "@user hello world" I wish I split into "@user" and "hello world". The contents of each substring is irrelevant, I just want to separate the original string into the first word and the remainder. It could also be "a b c d e f" into "a" and "b c d e f". How?

gator
  • 3,415
  • 8
  • 34
  • 72

2 Answers2

3

str.split() takes an optional second parameter for the max number of splits. Here you just want to split off the first item so you can use:

s = "@user hello world"
a, b = s.split(' ', 1)
a, b
# ('@user', 'hello world')
Mark
  • 84,957
  • 6
  • 91
  • 136
2

The split method with a parameter will do the job.

test_str = "This is a sentence"
print(test_str.split(' ', 1 ))
Rahul P
  • 2,173
  • 1
  • 13
  • 27