Hy guys this is my first time here.I am a beginner and i wantend to check how can i from a given string (which is: string="5,93,14,2,33" ) make a list, after that to get the square of each number from the list and than to return that list (with a squared values) in to string?
input should to be: string = "5,93,14,2,33"
output: string = "25,8649,196,4,1089"
i tried to make new list with .split() and than to do square of each element, but i understand that i didnt convert the string with int().I just cant put all that together so i hope that you guys can help.Thanks and sorry if this question was stupid, i just started learning
CodePudding user response:
Yes you started correctly.
# First, let's split into a list:
list_of_str = your_list.split(',') # '2,3,3,4,5' -> ['2','3','4','5']
# Then, with list comprehension, we transform each string into integer
# (assuming there will only be integers)
list_of_numbers = [int(number) for number in list_of_str]
Now you have your list of integers!
CodePudding user response:
You can do it using the following approach:
- Split the string of numbers into an array of integers
- Square them
- Convert them back to a string
- Join them to a string
- Print the output
# Input
input = "5,93,14,2,33"
# Get numbers as integers
numbers = [int(x) for x in input.split(",")]
# Stringify while squaring and join them into a string
output = ",".join([str(x ** 2) for x in numbers])
# Print the output
print(output)