0

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

2 Answers 2

5

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.')
Sign up to request clarification or add additional context in comments.

1 Comment

Nice, I had no idea there was a maxsplit argument. You learn something new every day.
1

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.

8 Comments

You don't need to do the wasteful rejoining at the end, you just need two splits.
Thank you! Very helpful. Quick question--does .split() make a list automatically? Or is that just pythons way to represent items separated from a string?
@RobertSchneeberger it makes a list automatically. In that code line is a string, and its method split returns a list that is then stored into parts.
This code gives me error could not convert string to float at thefloat = float(parts[1])
@RobertSchneeberger That error happens if the string is incorrectly formatted. There has to be a number there. The error will be something like ValueError: could not convert string to float: 'something' Does the string make sense? Is your file correct?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.