0

Here is my string

a = '(20.0, 8.0, 8.0, 37.0)'

and i want only first three items in this format

str = 20.0x8.0x8.0 

and store the last item in a list.

leftover = [37.0]

Earlier I had only three dimensions in the string so I was using replace function multiple times to convert it.

converted = str(''.join(str(v) for v in a)).replace("(","").replace(")","").replace(", ","x")

I know it's not the most pythonic way but it was doing the trick. But I have no clue how to remove an element from str(tuple)

Rahul Sharma
  • 2,187
  • 6
  • 31
  • 76

3 Answers3

4

Use ast.literal_eval:

import ast

a = '(20.0, 8.0, 8.0, 37.0)'

a_tupl = ast.literal_eval(a)

string = 'x'.join(map(str, a_tupl[:3]))  # 20.0x8.0x8.0
leftover = [a_tupl[-1]]  # [37.0]


Don't name your variable as str, because it shadows the built-in.
Austin
  • 25,759
  • 4
  • 25
  • 48
1

Try this :

from ast import literal_eval
str1 = "x".join([str(k) for k in literal_eval(a)[:3]])
leftover = [literal_eval(a)[-1]]

OUTPUT :

'20.0x8.0x8.0'
[37.0]

Without importing ast :

str1 = "x".join([k for k in a.replace("(","").replace(")","").split(",")[:3]])
leftover = [float(a.replace("(","").replace(")","").split(",")[-1])]
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
1

You can use simple LC over your splitted string to get back a list of values from the string representation of a tuple.
No libraries, just a simple python oneliner...:

a = '(20.0, 8.0, 8.0, 37.0)'

l = [float(v) for v in a[1:-1].split(',')]
# [20.0, 8.0, 8.0, 37.0]

Then it's as easy to create the two results you need:

str('x'.join([str(v) for v in l[:3]]))
# '20.0x8.0x8.0'

[l[-1]]
# [37.0]
SpghttCd
  • 10,510
  • 2
  • 20
  • 25