Python | slice string by character and not index

Python | slice string by character and not index

For getting only first word use index after splitting.

a=abcde!mdamdskm
print a.split(!)[0]
>>> 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]

Python | slice string by character and not index

Leave a Reply

Your email address will not be published. Required fields are marked *