Printing variables and strings in Python - python

I am trying to print the following lines :
'My name is John Smith.'
'My name is John Smith, and I live in CHICAGO'
and I live in chicago'
My code below :
name = 'John Smith'
age = 25
location = 'CHICAGO' # change this to lower case when printing
print('My name is %s.')
print('My name is %s, and I live in %s' )
print(f'My name is {name}.')
'and I live in location.lower()
How can I get the results from the top?

#!/usr/bin/env python3
name = 'john smith'
age = 25
location = 'chicago'
print ('My name is %s, and I live in %s. I am %s years old.' % (name, location, str(age)))
Output:
My name is john smith, and I live in chicago. I am 25 years old.
By the way i recommend you to read this article: https://realpython.com/python-string-formatting/

You can use f-strings for all of them. Use the lower() method to convert the location to lowercase.
print(f'My name is {name}')
print(f'My name is {name}, and I live in {location}')
print(f'and I live in {location.lower()}')

Related

Type Object '... ' has no attribute name '... '

I keep on getting the no attribute error in python. I want to make a class for cities to put into a program I am writing (Im trying to learn python on the side while working). I basically want to be able to put data into a class for cities and use that in another place. I guess, I would need to know how to access attributes from a class. Im probably doing a bunch wrong so any feedback would be helpful
class City:
def __init__(self, name, country, re_growth10):
self.name = name #name of the city
self.country = country #country the city is in
self.re_growth10 = re_growth10 #City Real estate price growth over the last 10 years
def city_Info(self):
return '{}, {}, {}'.format(self.name, self.country, self.re_growth10)
Toronto = City("Toronto", "Canada", 0.03) #Instance of CITY
Montreal = City("Montreal", "Canada", 0.015) #Instance of CITY
user_CityName = str(input("What City do you want to buy a house in?")) #user input for city
def city_Compare(user_CityName): #Compare user input to instances of the class
cities = [Toronto, Montreal]
for City in cities:
if City.name == user_CityName:
print(City.name)
else:
print("We Don't have information for this city")
return ""
print(City.name)
You are getting confused because you have a variable that has the same name as your class, City. To avoid this, use lower-case names for variables. Once you change this, you get a different error:
NameError: name 'city' is not defined
The reason is that you are trying to print the name of a variable which is defined inside a function, but the print statement is outside the function. To fix this, put your last print statement inside the function city_Compare, and call that function (which you never do).
Or change the function to return an object instead of printing it:
def find_city(name):
cities = [Toronto, Montreal]
for city in cities:
if city.name == name:
return city
return None
city_name = input("What City do you want to buy a house in?")
city = find_city(city_name)
if city is not None:
print(city.name)
else:
print("We Don't have information for this city")

How to alter user input?

So atm I'm making a table in python, and for it, I need the user to supply a name of a person for the table (e.g. David Beckham). However when the user has entered this and the table appears, the name needs to look like this: Beckham, David. How would I go about doing this?
With Python 3.6+ you can use formatted string literals (PEP 498). You can use str.rsplit with maxsplit=1 to account for middle names:
x = 'David Robert Bekham'
first_names, last_name = x.rsplit(maxsplit=1)
res = f'{last_name}, {first_names}'
# 'Bekham, David Robert'
Just store the input in a variable:
name = input()
first_name, last_name = name.split(" ")
table_value = last_name + ", " + first_name

Searching for a title thats 'starts with' in python?

So I have a list of names
name_list = ["John Smith", "John Wrinkle", "John Wayne", "David John", "David Wrinkle", "David Wayne"]
I want to be able to search, for example, John and
John Smith
John Wrinkle
John Wayne
will display. At the moment my code will display
John Smith
John Wrinkle
John Wayne
David John
What am I doing wrong?
Here is my code
search = input(str("Search: "))
search = search.lower()
matches = [name for name in name_list if search in name]
for i in matches:
if(search == ""):
print("Empty search field")
break
else:
i = i.title()
print(i)
Change your matches to:
matches = [name for name in name_list if name.startswith(search)]
You can also make some changes to your code:
# You can do this in one go
search = input(str("Search: ")).lower()
# Why bother looping if search string wasn't provided.
if not search:
print("Empty search field")
else:
# This can be a generator
for i in (name for name in name_list if name.startswith(search)):
print(i.title())

String interpolation working with python

I am new to learning how to use string interpolation in strings and am having trouble getting this example I am working with to actual print the right results.
I've tried to do:
print "My name is {name} and my email is {email}".format(dict(name="Jeff", email="me#mail.com"))
And it errors saying KeyError: 'name'
Then I tried using:
print "My name is {0} and my email is {0}".format(dict(name="Jeff", email="me#mail.com"))
And it prints
My name is {'email': 'me#mail.com', 'name': 'Jeff'} and my email is {'email': 'me#mail.com', 'name': 'Jeff'}
So then I tried to do:
print "My name is {0} and my email is {1}".format(dict(name="Jeff", email="me#mail.com"))
And it errors saying IndexError: tuple index out of range
It should give me the following output result back:
My name is Jeff and my email is me#mail.com
Thanks.
Just remove the call to dict:
>>> print "My name is {name} and my email is {email}".format(name="Jeff", email="me#mail.com")
My name is Jeff and my email is me#mail.com
>>>
Here is a reference on the syntax for string formatting.
You're missing the [] (getitem) operator.
>>> print "My name is {0[name]} and my email is {0[email]}".format(dict(name="Jeff", email="me#mail.com"))
My name is Jeff and my email is me#mail.com
Or use it without calling dict
>>> print "My name is {name} and my email is {email}".format(name='Jeff', email='me#mail.com')
My name is Jeff and my email is me#mail.com

Python. How to edit data in text database?

I have a little database text file db.txt:
(peter)
name = peter
surname = asd
year = 23
(tom)
name = tom
surname = zaq
year = 22
hobby = sport
(paul)
name = paul
surname = zxc
hobby = music
job = teacher
How to get all data section from for example tom? I want to get in variable:
(tom)
name = tom
surname = zaq
year = 22
hobby = sport
Then i want to change data:
replace("year = 22", "year = 23")
and get:
(tom)
name = tom
surname = zaq
year = 23
hobby = sport
Now add(job) and delete(surname) data:
(tom)
name = tom
year = 23
hobby = sport
job = taxi driver
And finally rewrite that changed section to old db.txt file:
(peter)
name = peter
surname = asd
year = 23
(tom)
name = tom
year = 23
hobby = sport
job = taxi driver
(paul)
name = paul
surname = zxc
hobby = music
job = teacher
Any solutions or hints how to do it? Thanks a lot!
Using PyYAML as suggested by #aitchnyu and making a little modifications on the original format makes this an easy task:
import yaml
text = """
peter:
name: peter
surname: asd
year: 23
tom:
name: tom
surname: zaq
year: 22
hobby: sport
paul:
name: paul
surname: zxc
hobby: music
job: teacher
"""
persons = yaml.load(text)
persons["tom"]["year"] = persons["tom"]["year"]*4 # Tom is older now
print yaml.dump(persons, default_flow_style=False)
Result:
paul:
hobby: music
job: teacher
name: paul
surname: zxc
peter:
name: peter
surname: asd
year: 23
tom:
hobby: sport
name: tom
surname: zaq
year: 88
Of course, you should read "text" from your file (db.txt) and write it after finished
Addendum to Sebastien's comment: use an in-memory SQLite DB. SQLite is already embedded in Python, so its just a few lines to set up.
Also, unless that format cannot be changed, consider YAML for the text. Python can readily translate to/from YAML and Python objects (an object composed of python dicts, lists, strings, real numbers etc) in a single step.
http://pyyaml.org/wiki/PyYAML
So my suggestion is a YAML -> Python object -> SQLite DB and back again.

Categories

Resources