7

I want to create variable from a long string to a small string.

e.g abcde!mdamdskm to abcde.

I know only what is the special character and not the index.

The Thonnu
  • 3,578
  • 2
  • 8
  • 30
ariel
  • 129
  • 1
  • 2
  • 4

2 Answers2

17

For getting only first word use index after splitting.

a="abcde!mdamdskm"
print a.split("!")[0]
Rohit-Pandey
  • 2,039
  • 17
  • 24
  • `split()`, not `slice()`! Thank you! btw fyi `partition()` will keep separator in the results – Denis Jan 28 '22 at 10:39
7
>>> "abcde!mdamdskm".split("!")
['abcde', 'mdamdskm']

This might not work if you have multiple instances of the special character:

>>> "abcde!mdam!dskm".split("!")
['abcde', 'mdam', 'dskm']

But you could fix that like this:

>>> "abcde!mdam!dskm".split("!", 1)
['abcde', 'mdam!dskm']
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241