My problem is that I want to convert this type of pieces of string into tuples. But I want the word to be a string and the number to be an integer. Is there some simple solution for this problem?
mystring = "(Ilioupoli,2)"
The output should be:
("Ilioupoli", 2)
I've been looking for some solutions but didn't find the solution for this one. I've found solutions to convert string of numbers into tuples with "map" but it doesn't fit well here.
CodePudding user response:
Remove the ()
around it, use split()
to split it at the comma, then convert the second element to an integer.
mystring = "(Ilioupoli,2)"
fields = mystring.strip("()").split(',')
mytuple = (fields[0], int(fields[1]))
CodePudding user response:
Use string replace to replace the ( and ) with nothing. Split the string on the ',' using string.split. Take the first element as a string, and convert the second using int or float. Then construct your tuple.
CodePudding user response:
mystring = "(Ilioupoli,2)".replace("(", "").replace(")", "").split(",")
tupl = (mystring[0], int(mystring[1]))