-1

I want to cast a tuple value with comma to string in python. Ex Input: 3,500.60 and output should be 3,500.6(string type)

value=3,500.60
s=str(value)

this returns (3, 500.6)

but I want like 3,500.6

Is it possible?

Vanjith
  • 520
  • 4
  • 23
  • 1
    You're parsing a tuple, it isn't a float. remove the comma – Sayse Apr 09 '19 at 13:18
  • 1
    There is no such thing as "a float value with comma" in Python. `3,500.6` is a tuple, consisting of the integer `3` and the float `500.6`. – jasonharper Apr 09 '19 at 13:19
  • 2
    3,500.60 is not a float. It is a tuple of the numbers 3 and 500.60. You can't use a comma as a thousands separator for numeric literals. You could use underscore if you wanted, though: `3_500.6` is equal to `3500.6`. – Kevin Apr 09 '19 at 13:19
  • actually that is a currency input. I shouldn't do that @sayse – Vanjith Apr 09 '19 at 13:20
  • 1
    when you are doing `value=3,500.60`, you are making value equal to a tuple that has elements `3` and `500.6` in it. – Kaiwen Chen Apr 09 '19 at 13:20
  • OK then how can i convert a currency to string in a simple way? – Vanjith Apr 09 '19 at 13:21
  • 1
    If this value is supposed to represent currency, I strongly recommend _not_ using a float to store it. Floats cannot accurately represent many numbers with two values past the decimal point. For example, the float 3500.6 is internally stored as `3500.59999999999990905052982270717620849609375`, and this imprecision can cause errors later on if you try to do arithmetic with it. Consider storing your currency as an integer number of cents, or perhaps use `decimal.Decimal`. – Kevin Apr 09 '19 at 13:22
  • Possible duplicate of [How to print number with commas as thousands separators?](https://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators) – Kaiwen Chen Apr 09 '19 at 13:22
  • Have you spelled your number incorrectly? Should it be `value = 3_500.60` as per PEP 515? – quamrana Apr 09 '19 at 13:24
  • Possible duplicate of [How to use digit separators for Python integer literals?](https://stackoverflow.com/q/38155177/1324033) – Sayse Apr 09 '19 at 13:26

1 Answers1

0

I asked a one liner expression which gives output like this. Anyway this one solved my problem.

value=3,500.60
b=''
for i in str(value):
    if not i in (' ','(',')'):
        b+=i
print(b)

UPDATE

This is what I want: Method 1:

print(str(map(lambda x:x if x not in ('(',')') else '',[i for i in value])).strip('[]').replace(' ',''))

Method 2:

print(str(value).strip('()').replace(' ',''))

All of them given result 3,500.6

Vanjith
  • 520
  • 4
  • 23
  • This is a very extreme way to allow you to keep using tuples in your code rather than actual numerical types. – Sayse Apr 09 '19 at 15:44