0

So i have this code where i'm creating a list with substrings: '''

string = "|01|12345|TEXT1|TEXT2|"

x = string.count("|")

if string.count('|') == 3:

    subst = string.strip('|').split('|')

    print(substr)

else:

    substr = string.strip('|').split('|')

    print(substr)

'''

Outcome:

'''

['01', '12345', 'TEXT1', 'TEXT2']

'''

However, i want to print all the substrings that the outcome is this:

'''

[LAS|01|G12345|TEXT1|TEXT2|<CR>|]

'''

I know i can just do:

'''

print("[LAS|" + substr[0] + "|G" + substr[1] + "|" + substr[2] + "|" + substr[3] + "|<CR>|]")

'''

But this is hardcoded, what if my the string that i get makes way more substrings? I do not want to use allot of if statements, if the count of ('|') == 4, == 5, == 6 etc.

How do i make sure that what i print contains all the substrings. And has a pipe symbol (|) in between every substring.

Thanks,

5 Answers5

1

Use str.split to make the substrings and str.strip to remove the potential leading and trailing pipes that will make you have empty substrings:

string = "01|12345|TEXT1|TEXT2|TEXT3|"

if string.count('|') == 3:
    # Do something
else:
    substrings = string.strip('|').split('|')
    # Do something
Adirio
  • 5,040
  • 1
  • 14
  • 26
0

Assuming you don't want the empty string before a 1st character vbar or the empty string after a final character vbar, I would try:

string = "01|12345|TEXT1|TEXT2|TEXT3|"
x = string.split("|")
if x[0] == "":
    x = x[1:]
if x[-1] == "":
    x = x[:-1]
James Shapiro
  • 4,805
  • 3
  • 31
  • 46
0

You could use the split method of a string.

string = "01|12345|TEXT1|TEXT2|TEXT3|"

substring = filter(lambda x: x =! '', string.split('|'))
print(substring)

Ahmed Tounsi
  • 1,482
  • 1
  • 14
  • 24
0

You can use that code

chain = "|01|12345|TEXT1|TEXT2|Text3|"

result = chain.strip('|').split('|')
Xeyes
  • 583
  • 5
  • 25
0

I think you want something like:

split_string = string.split("|")

If the variable string is:

 "aa|bb|cc|dd"

the variable split_string will be:

 ["aa","bb","cc","dd"]

Then, every index of the list "split_string" will be one of the substrings that you want.

Marco
  • 111
  • 3