Sama
Sama

Reputation: 55

Split text with split function

Im trying to split in python 3.6.

What I need is only abc-1.4.0.0

mytext = "_bla.blub = 'abc-1.4.0.0';"
#print(mytext)
mytext = str.split("_bla.blub = '");
#print (mytext)
print (mytext[1].split("'")[0])

but my result is empty. Why?

Upvotes: 0

Views: 207

Answers (5)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48120

Ideally you should be using regex module for such string related stuff. Below is the sample code to extract all the substrings between the single quotes from the given string:

>>> import re

>>> mytext = "_bla.blub = 'abc-1.4.0.0';"
>>> re.findall("'([^']*)'", mytext)
['abc-1.4.0.0']

Upvotes: 0

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

Try this simpler method (split by single quote):

mytext = "_bla.blub = 'abc-1.4.0.0';"
print(mytext.split("'")[1])

Upvotes: 0

seralouk
seralouk

Reputation: 33197

Do this:

mytext = "_bla.blub = 'abc-1.4.0.0';"
mytext = str.split(mytext);
mytext

['_bla.blub', '=', "'abc-1.4.0.0';"]

mytext[2]
"'abc-1.4.0.0';"

OR

mytext = "_bla.blub = 'abc-1.4.0.0';"

mytext = mytext.split("_bla.blub = '")

print (mytext[1].split("'")[0])
abc-1.4.0.0

OR

mytext = "_bla.blub = 'abc-1.4.0.0';"
mytext = mytext.split("'");
mytext

['_bla.blub', '=', "'abc-1.4.0.0';"]

mytext[1]
'abc-1.4.0.0'

Upvotes: 1

Simon
Simon

Reputation: 865

mytext = "_bla.blub = 'abc-1.4.0.0';"
print(mytext)
mytext = mytext.split("'");
print (mytext)
print (mytext[0])
print (mytext[1])

You need to call .split() on your string and save it into a variable instead of calling .split() on the strclass. Try this.

Upvotes: 1

You're not actually acting on mytext.

Try the following:

mytext = "_bla.blub = 'abc-1.4.0.0';"
#print(mytext)
mytext = mytext.split("_bla.blub = '")
#print (mytext)
print (mytext[1].split("'")[0])

Upvotes: 1

Related Questions