python - Send Return print to File.txt - python

How can I print return from functiion CheckTitle() to file .txt? This is code:
class all():
def __init__(self, driver):
super().__init__(driver)
self.full = ()
def CheckTitle(self, Pu, Not, Name):
today = str(date.today())
if self.driver.title == GeneralData.PUBLISHING_PAGE_TITLE:
print(Pu + Name + ', DATE: ' + today)
else:
print(Not + Name + ', DATE: ' + today)
def send_path(self):
with open('E:\PycharmProjects\Test\data\Result.txt', 'w') as f:
for pat in self.full:
f.write(pat)

def CheckTitle(self, Pu, Not, Name):
if self.driver.title == GeneralData.PUBLISHING_PAGE_TITLE:
return(Pu + Name + ', DATE: ' + today)
else:
return(Not + Name + ', DATE: ' + today)
def send_path(self):
with open('E:\PycharmProjects\Test\data\Result.txt', 'w') as f:
for pat in self.full:
f.write(pat)
f.write(CheckTitle('Pu -data','Not -Data','Frank'))
You need to have a return statement in the function.

Related

A little Tic-tac-toe program with the __str__ method, python 3

I have to write a Tic-tac-toe program with python and I use Jupyter Notebook. I want to write a class with the __str__ method. I've first try with a method I've called afficher, in the class Terrain. And it seem to work. But when I try with the __str__ method, it doesn't work.
class Case:
def __init__(self, a = ' '):
self.occupe = a
def jouer1(self):
if self.occupe == ' ':
self.occupe = 'X'
def jouer2(self):
if self.occupe == ' ':
self.occupe = 'O'
*** In need to replace the affiche methode by __str__ methode ***
class Terrain:
def __init__(self):
self.grille = []
for i in range(0, 9):
self.grille.append(Case())
self.tour = 1
def afficher(self):
for i in range(9):
if (i + 1)%3 != 0:
print(self.grille[i].occupe + ' | ', end =" ")
else:
print(self.grille[i].occupe)
def jouer(self, k):
if self.tour == 1:
self.grille[k].jouer1()
self.tour = 2
else:
self.grille[k].jouer2()
self.tour = 1
** this is the output I need, but with the __str__ method in the class Terrain**
terrain = Terrain()
terrain
terrain.jouer(3)
terrain.jouer(2)
terrain.jouer(4)
terrain.jouer(6)
terrain.jouer(5)
terrain.afficher()
*** this is how I replace the afficher method in the Terrain class (It doesn't work ... I don't know why ...) ***
class Case:
def __init__(self, a = ' '):
self.occupe = a
def jouer1(self):
if self.occupe == ' ':
self.occupe = 'X'
def jouer2(self):
if self.occupe == ' ':
self.occupe = 'O'
class Terrain:
def __init__(self):
self.grille = []
for i in range(0, 9):
self.grille.append(Case())
self.tour = 1
def __str__(self):
for i in range(9):
if (i + 1)%3 != 0:
return self.grille[i].occupe + ' | '
else:
return self.grille[i].occupe + ' \ '
def jouer(self, k):
if self.tour == 1:
self.grille[k].jouer1()
self.tour = 2
else:
self.grille[k].jouer2()
self.tour = 1
terrain = Terrain()
terrain
terrain.jouer(3)
terrain.jouer(2)
terrain.jouer(4)
terrain.jouer(6)
terrain.jouer(5)
print(terrain)
Sorry for my english.
Try the following for generating a string for the entire range rather than only one row
def __str__(self):
content = []
for i in range(9):
if (i + 1)%3 != 0:
content.append(self.grille[i].occupe + ' | ')
else:
content.append(self.grille[i].occupe)
return '\n'.join(content)
Thank you so much OneCriketeer.
I try this, and it works !
'
def str(self):
content = []
for i in range(9):
if (i + 1)%3 != 0:
content.append(self.grille[i].occupe + ' | ')
else:
content.append(self.grille[i].occupe + ' \n')
return ''.join(content)
'

How to instantiate a Room object called room1 and print with string representation of room1 in python?

I am doing a question where it is telling me to instantiate a Room object called room1 with size = 132, view = 'City', type = 'Double', and basicRates = 120. Then, I have to print a string representation of room1. How should I do this?
Like this?
class Room():
size = 0
view = ""
type_ = ""
basic_rates = 0
def __str__(self):
return 'Size: ' + str(self.size) + '\n' + 'View: ' + self.view + '\n' + \
'Type: ' + self.type_ + '\n' + \
'Basic Rates: ' + str(self.basic_rates)
room1 = Room()
room1.size = 132
room1.view = 'City'
room1.type_ = 'Double'
room1.basic_rates = 120
print(room1.__str__())
Also, you should read about Python Classes

Python: Calling a function with a string returns the description of the argument

I am trying to call a function with a string but as I do so the function just make use of the name of the argument for that function.
My function is defined as sortering(attribut) and when i call it with for example: sortering('age') it uses 'attribut' and not 'age'.
Here is the code, I am fairly new to python so it is probably something obvious that I am not familiar with.
def sortering(attribut):
try:
val1 = input("Vill du sortera stigande eller fallande? s/f")
if val1 == "s":
djurlista.sort(key=lambda x: x.attribut)
print(*djurlista,sep='\n' + ' ' + '\n')
elif val1 == "f":
djurlista.sort(key=lambda x: x.attribut, reverse=True)
print(*djurlista,sep='\n' + ' ' + '\n')
except ValueError:
print("Svara med s för stigande eller f för fallande!")
sortering('age')
The list "djurlista" is a list of strings and each string is an object 'Djur' with attributes: art, namn, ålder, kön, gravid
Here is that code:
class Djur:
def __init__(self, art, namn, ålder, kön, gravid):
self.art = art
self.namn = namn
self.age = ålder
self.gender = kön
self.gravid = gravid
x = Djur(art, namn, ålder, kön, gravid)
self.djurlista.append(x)
def __str__(self):
return ("Art: " + str(self.art) + " " + "\n"
"Namn: " + str(self.namn) + " " + "\n"
"Ålder: " + str(self.age) + " " + "\n"
"Kön: " + str(self.gender) + " " + "\n"
"Gravid: " + str(self.gravid))
def __repr__(self):
return str(self)
Instead of x.attribut (where attribut is a string, and x is a Djur instance), you should use [Python 3.Docs]: Built-in Functions - getattr(object, name[, default]):
djurlista.sort(key=lambda x: getattr(x, attribut))
Use x[attribut] and not x.attribut
def sortering(attribut):
try:
val1 = input("Vill du sortera stigande eller fallande? s/f")
if val1 == "s":
djurlista.sort(key=lambda x: x[attribut])
print(*djurlista,sep='\n' + ' ' + '\n')
elif val1 == "f":
djurlista.sort(key=lambda x: x[attribut], reverse=True)
print(*djurlista,sep='\n' + ' ' + '\n')
except ValueError:
print("Svara med s för stigande eller f för fallande!")
sortering('age')
It appears that you're trying to get the .attribut parameter from a global class/obj called x (via x.attribut), which should be throwing an error if it doesn't exist, but may not be if it's stored in your python cli somehow.
If you remove the x. before the reference to attribut, do you still get the same error?

Python string index out of range error?

I'm attempting to convert names from a first name first style to a family name first. The trick is getting it to accept input with or without a middle name.
My code as it stands:
import re
def convertName(oldName):
newName = oldName
while newName == oldName:
newName = re.sub('^ +', '',oldName)
newName = re.sub(' +', ' ',newName)
return newName
def main(firstName, middleName, lastName):
finalName = (lastName + firstName + middleName)
return finalName
name = 0
while name != "":
name = str(input("Name ---- "))
if name == "":
print("Finished")
break
newName = convertName(name)
firstNameSplit = newName.find(" ")
firstName = newName[:firstNameSplit]
lastNameSplit = newName.rfind(" ") + 1
lastName = newName[lastNameSplit:] + ', '
middleNameSplit = newName[firstNameSplit:lastNameSplit]
middleName = middleNameSplit.strip()
finalMiddleName = " " + middleName[0] + '.'
finalName = main(firstName, finalMiddleName, lastName)
print("Result --",finalName)
print()
My current results:
Name ---- joshua example example
Result -- example, joshua e.
Name ---- joshua example
Traceback (most recent call last):
line 37, in 0
builtins.IndexError: string index out of range
Any tips/hints would be much appreciated!!
Eventually found out a working solution in the following:
newName = convertName(name)
firstNameSplit = newName.find(" ")
firstName = newName[:firstNameSplit]
lastNameSplit = newName.rfind(" ") + 1
lastName = newName[lastNameSplit:] + ', '
middleNameSplit = newName[firstNameSplit:lastNameSplit]
middleName = middleNameSplit.strip()
if middleName != "":
finalMiddleName = " " + middleName[0] + '.'
else:
finalMiddleName = ""
finalName = main(firstName, finalMiddleName, lastName)
print("Result --",finalName)
print()
Or you could just do the following:
name = str(input("Name ---- "))
if len(name.split()) == 2:
print("Result -- " + name[name.rfind(" "):] + ", " + name[:name.find(" ")] + " " + name[name.find(" ")+1] + ".")
if len(name.split()) == 1:
print ("Result -- " + name[name.find(" "):] + ", " + name[:name.find(" ")])
else:
print ("Sorry! Invalid name")
This implementation has only been tested in Python 2.7.5.
It uses the string methods .find() and .rfind() to find the indices of the start of the first name, middle name, and last name
len(name.split()) tests how many words are in the name.
Your problem:
string = ""
print(string[0])
returns an error.
so, I fixed your main function, but you'll have to re-write the parser:
def main(firstName, lastName, middleName=""):
if(middleName == ""):
finalName = (lastName + " " + firstName)
else:
finalName = lastName + " " + firstName + " " + middleName[0] + "."
return finalName

Python Error Init of Class

Below is my code. It is giving me a compile error saying that artist has not been defined. This confuses me since artist is a parameter I'm passing.
Thanks.
class Track:
def __init__(self, artist, title, album=None):
self.artist = str(artist)
self.title = str(title)
self.album = album
def __str__(self):
return self.artist + " " + self.title + " " + self.album
def set_album(self, album):
self.album = album
class Album:
def init(self, artist, title, year='', genre='', tracks=None):
self.artist = str(artist)
self.title = str(title)
self.year = str(year)
self.genre = str(genre)
self.tracks = tracks
def __str__(self):
return self.artist + " " + self.title + " " + self.year + " " + self.genre + " " + self.tracks
def add_track(track):
self.tracks.append(track)
def music_library(tracks, albums):
while true:
command = raw_input("Please enter a command (s, st or sa)").lower()
if "s " in command:
searchText = command.split()(1)
elif "sa " in command:
searchText = command.split()(1)
elif "st " in command:
searchText = command.split()(1)
import os
from mutagen.mp3 import MP3
def load_library(dir):
for root, dirs, files in os.walk("."):
for filename in files:
if filename.lower().endswith(".mp3"):
fullname = os.path.join(root, filename)
print "\n%s" % fullname
try:
audio = MP3(fullname)
for key in audio:
print " %s: %s" % (key, str(audio[key]))
except:
print "Error on %s" % fullname
That is the entire file. I am running it using
python musiclib.py
I suspect it's because you're mixing tabs and spaces. When I copy and paste your code and look at it, I see:
' class Track:'
' \tdef __init__(self, artist, title, album=None):'
' \t\tself.artist = str(artist)'
' self.title = str(title)'
' self.album = album'
' '
' \tdef __str__(self):'
' \t\treturn self.artist + " " + self.title + " " + self.album'
' '
' \tdef set_album(self, album):'
' \t\tself.album = album'
Mixing tabs and spaces confuses Python about how far code is indented. Switch to using four spaces for indentation, and run your code using python -tt yourprogramname.py to confirm this diagnosis.

Categories

Resources