-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,465
  • 8
  • 36
  • 76

2 Answers2

4

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
  • 90,562
  • 7
  • 108
  • 148
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,493
  • 2
  • 17
  • 31