Reputation: 1
How would i use a function to grab specific parts of a string?
Say for instance my string consisted of data such as the following:
'12345678 123456.78 Doe, John D.' # Data that could be representative of bank software#
How do i tell python to make the first chars of the string an int, the second part of the string to be a float and the last part should automatically remain a string right?
for line in file_obj:
print(line) #would yield something like this '12345678 123456.78 Doe, John D.'
If i had functions like:
def find_balance():
return float
def find_acc_num():
return int
def find_name():
return str
What would my parameters be? Would for iteration be the best way to solve the problem? I want to be able to change account information (balances and names) as long as the user can supply the correct account number. I am new to using functions and am a bit unsure how to go about doing this...
Thanks in advance for any help i really appreciate it. =D
Upvotes: 0
Views: 104
Reputation: 4691
Probably homework but I am bored
for line in file_obj:
#Make a list of parts separated by spaces and new lines
#The second argument says to only split up the first two things
parts = line.split(None, 2)
#Assign each value
theint = int(parts[0])
thefloat = float(parts[1])
thestring = parts[3].strip()
You could do this in multiple functions by passing each function the parts if you wanted.
Edit: Changed code to use max length at suggestion of @arshajii . Also stripped the newline at the end of thestring.
Upvotes: 1
Reputation: 129477
You can use str.split()
with a maxsplit
of 2:
>>> s = '12345678 123456.78 Doe, John D.'
>>>
>>> v = s.split(None, 2)
>>> int(v[0]), float(v[1]), v[2]
(12345678, 123456.78, 'Doe, John D.')
Upvotes: 5