Reputation: 411
I'd like to take a user input about the delimiter and use it to split the data. I thought the line of code should look something like this:
my_delimiter = raw_input("write down the delimiter of your file(e.g. ','): ")
for line in file:
line2 = line.split(my_delimiter)
print line2
main_data.append(line2)
Then my sample input should be like
write down the delimiter of your file(e.g. ','): '\t'
and the output should be like
['age', 'prescript', 'astigmatic', 'tearRate\n']
['young', 'myope', 'no', 'reduced', 'no lenses\n']
but it remains the same. But it doesn't work. it is not delimited by tab or comma as I hope it to be. Please help me figure this out.
Upvotes: 0
Views: 651
Reputation: 329
>>> d = r'\t' # That's actual input you've got from user
>>> d
'\\t'
>>> d.decode('unicode-escape') # That's one you really want to use
u'\t'
Upvotes: 0
Reputation: 11
You may do this by using python's re module:
import re
my_delimiter = ",|\.|:"
my_txt = "this is, just a simple: txt"
delimited_list = re.split(my_delimiter, my_txt)
print delimited_list
the result will be like:
print delimited_list
['this is', ' just a simple', ' txt']
Upvotes: 0
Reputation: 116
If you are entering the values '\t' in the raw_input it turns them into the str '\t' which has 2 ascii characters. It doesn't turn '\t' into the tab character as you want. if for example, you know that you are going to get the input '\t' and you want to turn it into the tab character
my_delimiter = my_delimiter.replace('\\t', '\t')
this will change it into actual tab character. But then you would have to do it to all escaped characters like '\r' and '\n' and so on. What you should do is ask for the ascii values of the characters separated by a ','. In this case ask for the ascii value of '9' and turn it into int() and then into chr() and it should work.
Upvotes: 0
Reputation: 90899
If the user inputs \t
it will be coming as \\t
the backslash would be escaped and it can be interpreted as blackslash t
not tab
character.
To input the tab
character (\t
) , you should press the tab key and then press return
key.
Example -
>>> raw_input("Please input :")
Please input :\t
'\\t'
>>> raw_input("Please input :")
Please input :
'\t'
Note , in the second case, I pressed tab key and then return key.
Upvotes: 1