-1

I am trying to make python take a string, separate the characters before another character eg: "10001001010Q1002000293Q100292Q". I want to separate the string before each Q and have python create either a list or another string. I cannot figure this out for the life of me.

  • And what did you try in order to solve that? How did you try to figure things out? – user2736738 Sep 16 '21 at 03:06
  • `"10001001010Q1002000293Q100292Q".split('Q')` – ThePyGuy Sep 16 '21 at 03:08
  • FYI, calling `dir()` on your string, e..g `s='123Q456'; dir(s)` will give you a list of methods that a string supports. `split` and `partition` sound like something that divides strings. `help(split)` and `help(partition)` will give you a description of what they do. Try this out. – Mark Tolonen Sep 16 '21 at 03:23
  • Welcome to Stack Overflow. I tried literally [copying and pasting your question title into a search engine](https://duckduckgo.com/?tq=How+to+split+string+before+a+character+then+have+python+create+a+list+from+it). I got a page full of relevant and useful results, including video tutorials. For future reference, please note that a minimum of effort like this [is expected](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) before posting. Ideally a lot more. – Karl Knechtel Sep 16 '21 at 05:58
  • I searched like crazy and couldn't find anything about it. – Nikkolas1985 Sep 16 '21 at 14:22

2 Answers2

0

You can do this using the split function, give "Q" as a parameter to the split function then you can slice the list to only get the numbers before Q.

num = "10001001010Q1002000293Q100292Q"
print(num.split("Q")[:-1])

Split() function: https://www.w3schools.com/python/ref_string_split.asp
Slicing: https://www.w3schools.com/python/python_strings_slicing.asp

Tharu
  • 188
  • 2
  • 14
0

The syntax is str.split("separator").

str = str.split("Q")

Then output will be ['10001001010', '1002000293', '100292', '']. If you don't need the last empty element then you can write as:

str = str.split("Q")[:-1]
S.B
  • 13,077
  • 10
  • 22
  • 49