Search code examples
pythonstringspecial-characters

Get substring between two spesific characters in python


I am really confused that can't write a code that do this for me. Look This is my string:

a="hello | my friends| in | stack | over | flow"

I want to print "my friends" which is between first and second "|" Please help me


Solution

  • You could use string.split function.

    >>> a="hello | my friends| in | stack | over | flow"
    >>> a.split('|')[1].strip()
    'my friends'
    

    a.split('|')[1] prints the element at index 1 from the list which was created by splitting the input according to |.