Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List iteration
#1
Hi I am two week new in python.
I have one assigment:
string = "3,9,13,4,42"
This string I should convert into a list[].
after that squared each element of list (entire list)
Than that squared list to convert to string again
string="9,81,169,16,1764" # that is output at the end
Till now i do this :

string = '3,9,13,4,42'
string.split()
string = string.split()

I do not know how to make for loop and put on square.
does annybody can give me instruction ,to learn something

Thank you
Peca
Reply
#2
(Nov-11-2020, 08:08 AM)Peca Wrote: I do not know how to make for loop and put on square.
does annybody can give me instruction ,to learn something

Fire up your Python interactive interpreter and type help('for'), this way you learn how for-loop is operating. Next step could be entering help(str.split) to understand how this method is working and what arguments can be passed (to exit help press Q).

But before you start all this you should articulate the 'algorithm' how to achieve objective. I personally would do something like this:

- how to split string into digits
- how to convert digits in str datatype into integers
- how to square integers
- how to construct string from squared integers
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
There are multiple ways to solve this problem. It is a bit of a cheat, but a cheat that Python programs should know about.
Output:
>>> string = "3,9,13,4,42" >>> values = eval(string) >>> print(values) (3, 9, 13, 4, 42) >>> help(eval) Help on built-in function eval in module builtins: eval(source, globals=None, locals=None, /) Evaluate the given source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it.
I didn't know if this would work before I tried it. I assumed that running this program would give me a syntax error. But it works too.
values = 1, 2, 3, 4, 5
print(values)
Output:
(1, 2, 3, 4, 5)
Once you have a list of numbers it should be easy to write a for loop or list comprehension to square the values.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020