0

How can I get a string after and before a specific substring?

For example, I want to get the strings before and after : in

my_string="str1:str2"

(which in this case it is: str1 and str2).

Barmar
  • 741,623
  • 53
  • 500
  • 612
n1c0t1n3
  • 41
  • 1
  • 7

1 Answers1

1

Depending on your use case you may want different things, but this might work best for you:

lst = my_string.split(":")

Then, lst will be: ['str1', 'str2']

You can also find the index of the substring by doing something like:

substring = ":"
index = my_string.find(":")

Then split the string on that index:

first_string = my_string[:index]
second_string = my_string[index+len(substring):]
jj172
  • 751
  • 2
  • 9
  • 35