我打开一个文件'testFile'并将其拆分为逗号。到现在为止还挺好。一行中的第二个值是“30” 该行是“这是一个,30,测试” 我可以验证它是否正确分裂,因为我可以打印部件[1]并打印“30”,但为什么当该值为30时,repeats.isdigit()返回false?
with open('testFile') as fp:
for line in fp:
parts = line.split( ',' )
repeats = parts[1]
print repeats.isdigit()
print parts[1]
答案 0 :(得分:1)
isdigit()
将始终返回false,因为“30”之前的空白区域。要解决此问题,请在.strip()
isdigit()
方法
答案 1 :(得分:0)
You could use re.split. it can split on mult tokens.
import re
with open('data') as f:
for line in f:
# split on white space and commas
line = re.split(r'[ ,]',line)
# re.split leaves some empty strings, so remove them
line = [el for el in line if el]
print(line)
print(line[3].isdigit())
['This', 'is', 'a', '30', 'test']
True