DoubleDecker
DoubleDecker

Reputation: 25

How to split using delimiter saved in a variable

I have a script where I want the user to input the delimiter on which every line in the file should be split. However, once I save this delimiter in a variable, I can no longer use it as a delimiter in the split() function. Any workarounds?

Example which does not work:

a='"\t"'
my_line.split(a)

Upvotes: 1

Views: 107

Answers (5)

ravishankar chavare
ravishankar chavare

Reputation: 503

    my_line='No suggested  \tjump to results Extension \tfor detecting mobile devices, managing   mobile view'
    a='\t'
    print(my_line.split(a))

**RESULT:**  ['No suggested  ', 'jump to results Extension ', 'for detecting mobile devices, managing   mobile view']

you can also use a="\t" or a='\t' instead of combination

Upvotes: 0

clamentjohn
clamentjohn

Reputation: 3987

In python a string object is anything that comes within a single-quote or single-quote, or something inside two of this """ or this '''. The method split expected a string object to be its parameter

string.split(s[, sep[, maxsplit]]) 

Link to doc

What you've passed in is a '"\t"'So it's a "\t" string.

You might have been confused when it came to quotes, but understanding what a method expects as an argument (reading the docs help) and understanding the the python docs will help you. Basically, read the docs.

TL;DR
Use

a = '\t' #if you wanted to use TAB as the delimiter
#Remember it's expecting a string obj

Upvotes: 0

Aneesh Palsule
Aneesh Palsule

Reputation: 337

@DoubleDecker Hi, in your line of code, you have a='"\t"'. If you make a either a="\t" or a='\t' then your code will work fine. Writing a='"\t"' is not the same as the two above.

>>> a = '"\t"'
>>> a
'"\t"'
>>> b = "\t"
>>> b
"\t"
>>> c = '\t'
>>> c
'\t'
>>> a == b
False
>>> a == c
False

Hope this helps.

Upvotes: 0

Tezirg
Tezirg

Reputation: 1639

That because you are making a delimiter that's 3 chars long ' + \t + ' instead of one \t.

Try with:

a="\t"
my_line.split(a)

Upvotes: 3

Jay
Jay

Reputation: 24905

You seem to have extra quotes in your delimeter. split takes those additional ' also as a part of your delimiter causing issues. split ends up searching for '\t' instead of \t as expected by you.

a="'\t'"

should be

a="\t"

Upvotes: 4

Related Questions