Invictus
Invictus

Reputation: 4328

Splitting a string in Python

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

Upvotes: 0

Views: 4192

Answers (3)

Bas Wijnen
Bas Wijnen

Reputation: 1318

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.

Upvotes: 0

khachik
khachik

Reputation: 28703

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.

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

just use strip():

In [34]: strs="    I_AM_SAM,"

In [35]: strs.strip(" ,") # pass a space " "and "," to strip
Out[35]: 'I_AM_SAM'

Upvotes: 2

Related Questions