0

I have a list of strings where all of the strings roughly follow the format 'foo\tbar\tfoo\n' in that there are three segments of variable length that are separated by two tabs (\t) and with a newline indicator at the end (\n).

I want to remove everything except for the text before the first \, so that it would return as 'foo'. Given that the first segment is of variable length, I'm not sure how I can do that.

3 Answers 3

1

Use str.split():

>>> string = 'foo\tbar\tfoo\n'
>>> string.split('\t', 1)[0]
'foo'

This splits the string by the first occurrence of the '\t' tab character, which returns a list with two elements. The [0] selects the first element in the list, which is the part of the string before the first '\t' occurrence.

Sign up to request clarification or add additional context in comments.

1 Comment

Re-using the string name strikes me as a bad idea.
0

Just search for the first \t character, and get everything before it. Slicing makes this easy.

newstr = oldstr[:oldstr.find("\t")]

Comments

0

Try with:

t = 'foo\tbar\tfoo\n'
t[:t.index("\t")]

2 Comments

sorry, I forgot to make clear that 'foo', 'bar', and 'foo' are all of variable length.
@user3801997 What the code above does is to find the index of the first appearance of \t and return the heading string to that index so this code manages correctly variable length of whatever word you have as long as you have \t within your string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.