Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In python, I understand it's possible to convert many types of data to a string using str(). Is there any way to reverse this? Let me show you what I mean.
exampleDictionary = {'thing on ground': 'backpack'}
backpack = {'tea': 'Earl Grey'}
def openBackpack():
#code to grab backpack from exampleDictionary
#code to convert 'backpack' to backpack
#code to access backpack and look at the tea
This is oversimplified of my code in progress, but it should be easy to see basically where I'm stuck at. If it's not clear I'm happy to clarify further.
This is a very weird way to handle data.
I would use a nested dicts:
exampleDictionary = {'thing on ground': {'backpack': {'tea': 'Earl Grey'}}}
print exampleDictionary['thing on ground']
print exampleDictionary['thing on ground']['backpack']
print exampleDictionary['thing on ground']['backpack']['tea']
Outputs:
{'backpack': {'tea': 'Earl Grey'}}
{'tea': 'Earl Grey'}
Earl Grey
You're looking for globals().
def openBackpack():
backpack= globals()[exampleDictionary['thing on ground']]
print(backpack['tea'])
This approach looks up the string for and already existing object in the code.
exampleDictionary = {'thing on ground': 'backpack'}
backpack = {'tea': 'Earl Grey'}
print( eval(exampleDictionary['thing on ground']) )
edit
to Adam Smith 's point eval isn't a safe and you shouldn't do this
... but it can be done and here is how.
eval https://docs.python.org/2/library/functions.html#eval
takes a string and interprets it as code.
x = eval("1+2")
x = 3
if you eval user input the likelyhood you know all of what a user can input or 'inject' into your code is unknown.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
As we all know that All fundamental datatypes in python are immutable and we can't change anything in them,
If I try to replace something in fundamental data types I will definitely get an error. Take an example from this;
#TRYING TO REPLACE AN INTEGER FROM A VARIABLE.
num=123456789
1=78
print(num)
OUTPUT:
File "D:\myPractice.py\sideRun.py", line 2
1=78
^
SyntaxError: cannot assign to literal
If fundamental data types are immutable, then why is the string has replace() inbuilt function.
**#REPLACING A OLD STRING WITH A NEW STRING**
s="Jimmy is a student of CS and Jimmy is a boy "
print(id(s))
print(s.replace("CS","SE"))
print(id(s))
In this, both of print() statements that have ID argument are giving the same output that is the same address.
**MY QUESTIONS ARE**
If the string data type is immutable then why it has 'replace()' function?
If a new object is created due to 'replace()' function then why new and old string has the same ID?
str.replace(...) returns a modified copy of the given string. This method doesn't mutate your "s" variable.
s = "Jimmy is a student of CS and Jimmy is a boy "
s1 = s.replace("CS","SE")
print(id(s))
print(id(s1))
# your script did nothing but printed ids
# in this case s1 contains modified copy of string "s"
# script will print different ids
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm currently scraping some tables on the internet where numbers are posted in varying numerical formats:
Animal - Left in Wild
Tigers - 18
Deer - 18m
Pigs - 180000
I've managed to strip the m away from the number, but I am wondering if/how I could use a if statement to allow some manipulation to ensure I document the number accurately:
if animal.strip("m") == animal.strip("m"):
left_in_wild = left_in_wild * 1000000
Obviously that code does not work, but it is a rough thought of how I'm thinking about getting around this. If anyone can has anything they think can be helpful let me know.
Thank you!
A simple IF statement could help with what you're looking for:
animal = "18m"
if 'm' in animal:
print animal.strip('m') + ",000,000"
if 'k' in animal:
print animal.strip('k') + ",000"
returns:
18,000,000
Something like:
import re
def get_number(s):
try:
i=int(re.match('(\d+)', s).group(1))
if "m" in s:
i*=1000000
return i
except:
print "No Number"
get_numbers("18m") returns 18000000
You could even expand it to have an elif "k" in s block if you had thousands or something.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
this is the example of the program
hello1,hello2,hello3,hello4,hello5=(),(),(),(),()
a_list=[hello1,hello2,hello3,hello4,hello5]
greetingslist= ["hello","good morning","good evening","afternoon","hi"]
for i range 5:
a_list[i]=greetingslist[i]
so I want each variable identifier to be different so that each can be assigned something. However it doesn't recognize the [i] next to the variable so an error occurs.
I don't want to change the program much or make it too complicated, but I would like this to be done within one loop...is there any way I could do this???
thanks in advance!
You're just storing references to your variables, which you override in the loop. If you want to dynamically set the variables by their name, you'll have to use globals()/locals()/setattr() in dependence of the namespace, e.g.:
greetings_list = ["hello", "good morning", "good evening", "afternoon", "hi"]
for i, v in enumerate(greetings_list):
locals()["hello" + str(i + 1)] = v
print(hello1) # hello
print(hello2) # good morning
print(hello3) # good evening
print(hello4) # afternoon
# etc.
Not that it's a recommended style or anything, far from it, but that's how you can do it.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Hey i don't know how to explain this so i will give an example.
print("hey eating # is a good idea")
What i want to happen is that when you type something. (answer = raw_import)
The # is what you typed.
Like if you typed orange. It would say ("hey eating orange is a good idea")
Also i want this to be after an else: statement.
I hope you understand my question.
This could be used for games, and other programs too. I bet many people have the same question and don't know what to google! Thanks!
Check this out. http://www.python-course.eu/python3_formatted_output.php
fruit = "orange"
say = "hey eating {0} is a good idea".format(fruit)
print(say)
Use str.format
say = "hey eating {} is a good idea"
if some_condition:
# do something
else:
a = raw_input("Enter your favourite fruit!")
print s.format(a)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to figure out how to compare a string to the 0th element in the list (technically the bottom). The list is also a class instance and looks like this:
#define class called GEL
class GEL:
def __init__(self,eventtime,type):
self.eventtime=eventtime
self.type=type
myList=[]
And when I add something to the list:
myList.append(GEL(time,type)) ##Type can be either 'Arrival' or 'Departure'
For which the list will be (1.343432,'Arrival')
So I want to compare 'Arrival' with the type item in the list.
for i in range(5): ##loop for insertions and deletions
Type=[a.type for a in myList] ##Actually goes to the last type, but want first
if 'Arrival' in Type:
##DO STUFF
else:
##HELLO WORLD
#sortlist
myList.pop(0)
What would be the correct way just get the first type in the list?
Sorry for the poor jargon, am still learning Python.
EDIT: I think I may have solved. It gets me what I want. If anyone could tell me if this would be ok:
if 'Arrival' in Type[0]:
I think you just need this
if mylist[0].type == 'Arrival':