2012-11-23 56 views
0

我有一個字符串,它是####I_AM_SAM,。我想要的只是使用文本部分。所以我試圖使用split並將其拆分爲:line = f.readline().split(',' ,' ')其中f.readline()讀取此「I_AM_SAM」。我期望line [0]獲取文本,但是這給了我一個錯誤。請注意,在文本「I_AM_SAM」之前有4個空格。我用「#」符號表示空格鍵。在Python中分割字符串

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

TypeError: an integer is required

+0

你期待輸出是什麼? – NPE

+0

我編輯過我的問題,在'I_AM_SAM,'之前有4個空格。我想爲我提取I_AM_SAM – Invictus

回答

3

只需使用strip()

In [34]: strs=" I_AM_SAM," 

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

strs =「#### I_AM_SAM」,而不是strs =「I_AM_SAM」,「#」代表空格鍵 – Invictus

+0

@Invictus解決方案已被編輯。 –

2
line = f.readline().split(',' ,' ') 
    TypeError: an integer is required 

由第二個參數split引起的,它必須是一個整數:

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.

在你的情況需要line = f.readline().split(',')[0]。另外,請考慮使用re.sub

0

Split有兩個參數,第一個是分隔符,第二個是分裂的最大數量。所以這個代碼:

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

將導致三個字符串:'你好','有','這是一條線'。

你想省略第二個參數,或使其成爲1(不確定,你的描述不夠清晰)。如果您想要分割多個角色,則需要多次調用才能分割。

如果這不是您所期望的答案,請讓問題更清楚:您期望得到什麼?你把第二個參數放在split中的原因是什麼?還有一件事:如果文字字符串中的空格是一個製表符,請將其寫爲\ t以便閱讀。