Hello,
Can someone please help me with a little problem that I am having splitting strings?
I am trying to remove everything more than 2 - digits to the right of a decimal point in a string.
For some reason I am not realizing my desired results. If you could just give me a few hints without giving me the answer I would greatly appreciate it.
Thank You,
HR

# This program demonstrates the split method.

def main():
   # Create a string with multiple words.
   my_string = '1247.123456789'

   # Split the string.
   number_list = my_string.split('.')
   secondString = number_list[1:2]

   secondString = secondString[0 : 2]
   print(secondString)

# Call the main function.
main()

Recommended Answers

All 7 Replies

secondString = number_list[1:2] will give you a list that contains the second string as its only element. Then when you do secondString[0:2] you're saying "take the first two elements of this list", but the list only has one element, so you get the same list back unchanged.

What you want is for secondString to be the string directly and not a list containing the string. So you should be doing secondString = number_list[1].

Thanks sepp2k. I will play around with this.
HR

This program demonstrates the split method.

def main():

Create a string with multiple words.

my_string = '1247.123456789'

Split the string.

number_list = my_string.split('.')
secondString = number_list[1:2]
secondString = secondString[0 : 2]
print(secondString)

Call the main function.

main()

Hello sepp2k,
It works just like you said it would, thanks.
It still strikes me as odd that when I printed secondString right after the statement
secondString = number_list[1:2]
I would get the second string.

I guess it's still just one element. For instance when I replace [1:2] with [0] I will get the first two digits in the first string of numbers.

I really do appreciate this little tutorial sepp2k.
HR

Hope this solves this, if your desired output is 1247.12:

# This program demonstrates the split method.

def main():
# Create a string with multiple words.

    my_string = '1247.123456789'

# Split the string.   

    number_list = my_string.split('.')  
    print number_list

    firstString = number_list[0]
    print firstString
    secondString = number_list[1]
    secondString = secondString[0 : 2]   
    print(secondString)

    final_string = firstString + '.' + secondString
    print final_string
# Call the main function.

main()

There is also

my_string[:my_string.index('.') + 3]

or

"{0:.2f}".format(float(my_string))

but the program no longer illustrates the split() method.

Peter Parker's code is exactly how I did mine last night. Griboullis's code is what I was striving for but could not figure out.
Thanks to all.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.