string - Get only one word from line -


how can take 1 word line in file , save in string variable? example file has line "this, line, is, super" , want save first word ("this") in variable word. tried read character character until got on "," when check got error "argument of type 'int' not iterable". how can make this?

line = file.readline() # reading "this, line, is, super"     if "," in len(line): # checking, if contains ','         in line:             if "," not in line[i]: # while character not ',' -> error                 word += line[i] # add string 

at glance, on right track there few things wrong can decipher if consider data type being stored where. instance, conditional 'if "," in len(line)' doesn't make sense, because translates 'if "," in 21'. secondly, iterate on each character in line, value not think. want index of character @ point in loop, check if "," there, line[i] not line[0], imagine, line['t']. easy assume integer or index in string, want range of integer values, equal length of line, iterate through, , find associated character @ each index. have reformatted code work way intended, returning word = "this", these clarifications in mind. hope find instructional (there shorter ways , built-in methods this, understanding indices crucial in programming). assuming line string "this, line, is, super":

if "," in line: # checking string, not number 21, has comma     in range(0, len(line)): # each character in range 0 -> 21         if line[i] != ",": # e.g. if line[0] not equal comma             word += line[i] # add character string         else:             break # break out of loop when encounter first comma, storing first word 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -