Home > Back-end >  Split "" in a str py
Split "" in a str py

Time:06-23

so i got this question and it´s I have a str like this:

"Factura,FE8868""Valor,795,000.00,850,000.00,140,000.00,1,450,000.00""Total,3,235,000.00""CECO,101,0,111,105""PLANILLAS,21999/21300/21304/23975/23946/25706/25714/23966/23977/23913/23941"

And what i want to split every "" to get sometime like this: (A variable for each split result)

n1 = "Factura,FE8868"
n2 = "Valor,795,000.00,850,000.00,140,000.00,1,450,000.00"
n3 = "Total,3,235,000.00" 
n4 = "CECO,101,0,111,105"
n5 = "PLANILLAS,21999/21300/21304/23975/23946/25706/25714/23966/23977/23913/23941"

Note, if i try to declarate a variable with the whole str before split it, get an error due a variable is var = "some in here" and this one would looks like var = " "some""thing""here" "

How could i do it?

CodePudding user response:

A few ways you can achieve this.

Use single quotes: ' (assuming you don't have any ' in the string itself)

var = '" "some""thing""here" "'

Use triple-quotes (either ''' or """)

var = """"" "some""thing""here" """"

You can also do this by escaping " with \" when they're part of the string (but probably the least aesthetic solution):

var = "\" \"some\"\"thing\"\"here\" \""

data = '"Factura,FE8868""Valor,795,000.00,850,000.00,140,000.00,1,450,000.00""Total,3,235,000.00""CECO,101,0,111,105""PLANILLAS,21999/21300/21304/23975/23946/25706/25714/23966/23977/23913/23941"'

# split('"') on the original string does not result in
# what you want based on your question (e.g. leading " is
# considered a 'split' that ends up being an empty string
# Because the string you gave us begins with a leading "
# and ending ", one way to do what you want is to split
# and then remove any empty fields in the resulting split

n1, n2, n3, n4, n5 = [i for i in data.split('"') if i]

print(n1)
print(n2)
print(n3)
print(n4)
print(n5)

CodePudding user response:

First, when you write your code, use single quotes when declaring the string. That way, the double quotes in the string won't make python thing the string has finished.

Then you can split your string easily. Try this:

s = '"Factura,FE8868""Valor,795,000.00,850,000.00,140,000.00,1,450,000.00""Total,3,235,000.00""CECO,101,0,111,105""PLANILLAS,21999/21300/21304/23975/23946/25706/25714/23966/23977/23913/23941"'
s.split('""')
  • Related