0

I have a string which is ####I_AM_SAM,. What I want is to use only the text part. So I was trying to use split and split it like this: line = f.readline().split(',' ,' ') where f.readline() reads this " I_AM_SAM,". I expected line[0] to fetch the text, but this gives me an error. Note that there are 4 spaces before the text "I_AM_SAM". I have represented the space bar with a "#" symbol.

line = f.readline().split(',' ,'    ')

TypeError: an integer is required

2
  • What are you expecting the output to be? Commented Nov 23, 2012 at 14:19
  • I have edited my question there are 4 spaces before I_AM_SAM, . I want to extract I_AM_SAM Commented Nov 23, 2012 at 14:21

3 Answers 3

2

just use strip():

In [34]: strs="    I_AM_SAM,"

In [35]: strs.strip(" ,") # pass a space " "and "," to strip
Out[35]: 'I_AM_SAM'
Sign up to request clarification or add additional context in comments.

1 Comment

for me strs="####I_AM_SAM," and and not strs="I_AM_SAM," wher # represent spacebar
2
line = f.readline().split(',' ,'    ')
  TypeError: an integer is required

is caused by the second argument to split, it must be an integer:

S.split([sep[, maxsplit]]) -> list of strings

Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are\nremoved from the result.

In your case you need line = f.readline().split(',')[0]. Also, consider using re.sub.

Comments

0

Split takes two arguments, the first being the separator to split on, the second the maximum number of splits it does. So this code:

'Hello there, this is a line'.split (' ', 2)

will result in three strings: 'Hello', 'there,' and 'this is a line'.

You want to omit the second argument, or make it 1 (not sure, your description is not clear enough). If you want more than one character to split on, you need multiple calls to split.

If this isn't the answer you expected, please make the question more clear: what do you expect to get? What is the reason you put the second argument in split? And one more thing: if that space in the literal string is a tab, please write it as \t for readability.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.