I need to print this list without the commas, but I can't seem to figure out how.
data = (
('Sabrina Bryan,1/3/98,ss9387,f9;s1;m1,99km'),
('Fergus Connon Archer,11/21/89,ss5246,f1;s3,102km'),
('Adrian Harvey,3/3/78,ss1654,m5;s2,72km'),
('Patricia Abigail Wolf,9/5/00,ss0936,f3;s4;m8,134km'),
('Georgina Kramer,6/15/95,ss4837,f5;s2;m1,55km'),
('Glenn Julian Ayala,3/19/90,ss3689,s4;f3,152km'),
('Anita Davila,6/27/91,ss9367,f8,203km'),
('Gertrude Nunez,1/12/97,ss3948,s3;m1,34km'),
('Solomon Burton,8/5/88,ss7364,s2;f1,23km'),
('Rafael John Murray,10/19/01,ss9105,s9;f3,78km')
)
info = input("What would you like to do? ")
if info == 'b':
for line in data:
fname0 = data[0].split(' ')
lname0 = fname0[1].split(',')
bday0 = lname0[1].split('/')
def Sabrina(fname0, bday0):
print(fname0[0], *bday0[0:2], sep = ', ')
print(Sabrina(fname0, bday0))
It is printing "Sabrina, 1, 3" when I want it to print "Sabrina 1 3". I have tried using the .replace command, *bday0[0:2].replace(',', ' '), but it just gives me an error. Any tips?
You don't need .replace().
print(fname0[0], *bday0[0:2])
or
print(fname0[0], *bday0[0:2], sep = ' ')
will give you the desired output.
I figured out a quick solution for your problem:
It is based on the use of F-Strings. With this formatting-solution, you can quickly format your strings by implementing your variables without losing sight of the format of your output, also adding a return to the function.
Function Code Snippet
def Sabrina(fname0, bday0):
return f"{fname0[0]}, {bday0[0]} {bday0[1]}"
Here is more information related to the f-strings formatting explained.
It would be a great improvement if you could work around the issue that the values are hardcoded. But for a quick implementation this should help.
Let me know if this answers your question.
Cheers!
Full Working Code-Snippet
data = (
('Sabrina Bryan,1/3/98,ss9387,f9;s1;m1,99km'),
('Fergus Connon Archer,11/21/89,ss5246,f1;s3,102km'),
('Adrian Harvey,3/3/78,ss1654,m5;s2,72km'),
('Patricia Abigail Wolf,9/5/00,ss0936,f3;s4;m8,134km'),
('Georgina Kramer,6/15/95,ss4837,f5;s2;m1,55km'),
('Glenn Julian Ayala,3/19/90,ss3689,s4;f3,152km'),
('Anita Davila,6/27/91,ss9367,f8,203km'),
('Gertrude Nunez,1/12/97,ss3948,s3;m1,34km'),
('Solomon Burton,8/5/88,ss7364,s2;f1,23km'),
('Rafael John Murray,10/19/01,ss9105,s9;f3,78km'))
info = input("What would you like to do? ")
if info == 'b':
for line in data:
fname0 = data[0].split(' ')
lname0 = fname0[1].split(',')
bday0 = lname0[1].split('/')
def Sabrina(fname0, bday0):
return f"{fname0[0]} {bday0[0]} {bday0[1]}"
print(Sabrina(fname0, bday0))
Related
I'm very new to programming, only started learning python ~4 days ago and I'm having trouble figuring out how to print a user input as a string, in between other strings on the same line. Being so new to programming, I feel like the answer is staring me right in the face but I don't have the tools or the knowledge to figure it out lol.
what I'm trying to do is:
Wow (PlayerName) that's cool
so far what I have is:
name = input("Name? ")
print("Wow") (print(name)) (print("that's cool"))
python came back with an error saying object 'NoneType' is not callable, so instead i tried to write it as a function and call that instead:
name = input("Name? ")
def name_call():
print(name)
print("Wow") (name_call()) (print("that's cool"))
same issue, I tried various similar things, but at this point I'm just throwing darts
I'm not 100% sure why neither of these worked, but I do know that it probably has something to do with me writing it incorrectly. I could just print the name on a new line, but I want to try and put them all on the same line if possible.
you can try this code:
# Python3 code to demonstrate working of
# Add Phrase in middle of String
# Using split() + slicing + join()
# initializing string
test_str = 'Wow that\'s cool!'
# printing original string
print("The original string is : " + str(test_str))
# initializing mid string
mid_str = (input('Please input name = '))
# splitting string to list
temp = test_str.split()
mid_pos = len(temp) // 3
# joining and construction using single line
res = ' '.join(temp[:mid_pos] + [mid_str] + temp[mid_pos:])
# printing result
print("Formulated String : " + str(res))
The result will be like this:
The original string is : Wow that's cool!
Please input name = Alice
Formulated String : Wow Alice that's cool!
you can input any name to the program.
As others have said, I think you're looking for string interpolation. As of Python 3.6 we have f-strings.
name = input("Name? ")
print(f"Wow {name} that's cool")
https://www.programiz.com/python-programming/string-interpolation
Your print's need to be on new lines.
name = input("Name? ")
print("Wow")
print(name)
print("that's cool")
Python thinks you are trying to call the result of the print function (which returns None) as a function of its own.
|
V you are accidentally calling the return value here
print("Wow")(print(name))
val = 'name'
print(f"Wow {val} that's cool.")
Btw, if you want name_call() to play a role, the following code also works
def name_call():
return ('name')
print(f"Wow {name_call()} that's cool.")
You may use the format method to insert name into the string's placeholder {}:
print("Wow {} that's cool".format(str(name)))
x = str(input('Name: '))
print('user entered {} as their name'.format(x))
Say for example i have a list of lists that contain data like this:
customer1 = ['Dan','24','red']
customer2 = ['Bob',' ','Blue']
customerlist = [customer1, customer2]
I would like to run a line of code that will run a function if one of these elements is empty. For example something like this:
for c in customerlist:
if not in c:
***RUN CODE***
else:
print('Customer Complete')
That way if a customer is missing data i can run some code.
Thanks for the help!
Instead of this:
if not in c:
You want this:
for val in c:
if not val.strip():
Which basically checks if any of the strings is empty (empty strings are "falsey" in Python). Stripping first detects strings which only contain whitespace.
You can use in to check for ' '
for c in customerlist:
if ' ' in c:
RUN CODE
else:
print('Customer Complete')
Both of the answers given by Guy and John are correct, but perhaps it would interest you to look into objects:
class Customer:
def __init__(self, name, age = None, color = None):
self.name = name
self.age = age if age else age_function_generator()
self.color = color if color else color_function_generator()
To create a customer, then, simply do:
c1 = Customer(name = "Dan", age = 24, color = "red")
c2 = Customer(name = "Bob", color = "Blue")
In the case of c2 the function age_function_generator() (not defined here) would be called. To access the attributes of the customer object one would do:
print(c1.name, c1.age, c1.color)
You may use Python Regular Expression to search for blank entries on the list. A Regular Expression is a sequence of characters that define a pattern. For more information on Python Regular Expression, kindly visit:
w3school link and Google Developer link
Kindly replace the following code
for c in customerlist:
if not in c:
with the following code:
for i in range(len(customerlist)):
for j in range(len(customer1)):
emptylist = re.findall('\s*', customerlist[i][j])
Dont forget to include 'import re' at the beginning of code to import Python re module
The complete code:
import re
customer1 = ['Dan','24','red']
customer2 = ['Bob',' ','Blue', ' ']
customerlist = [customer1, customer2]
for i in range(len(customerlist)):
for j in range(len(customer1)):
emptylist = re.findall('\s*', customerlist[i][j])
if(len(emptylist) == 0):
print('There are no blank entries')
else:
print('There are blank entries')
#code goes here to do something
The output:
There are blank entries
In the code:
emptylist = re.findall('\s*', customerlist[i][j])
re.findall() search for zero or more instances(*) of white space character(\s) with customerlist being the iterating list. customerlist[i][j] as it is a list of lists.
I wrote a script for system automation, but I'm getting the error described in the title. My code below is the relevant portion of the script. What is the problem?
import csv
import os
DIR = "C:/Users/Administrator/Desktop/key_list.csv"
def Customer_List(csv):
customer = open(DIR)
for line in customer:
row = []
(row['MEM_ID'],
row['MEM_SQ'],
row['X_AUTH_USER'],
row['X_AUTH_KEY'],
row['X_STORAGE_URL'],
row['ACCESSKEY'],
row['ACCESSKEYID'],
row['ACCESSKEY1'],
row['ACCESSKEYID1'],
row['ACCESSKEY2'],
row['ACCESSKEYID2'])=line.split()
if csv == row['MEM_ID']:
customer.close()
return(row)
else:
print ("Not search for ID")
return([])
id_input = input("Please input the Customer ID(Email): ")
result = Customer_List(id_input)
if result:
print ("iD: " + id['MEM_ID']
For the line
line.split()
What are you splitting on? Looks like a CSV, so try
line.split(',')
Example:
"one,two,three".split() # returns one element ["one,two,three"]
"one,two,three".split(',') # returns three elements ["one", "two", "three"]
As #TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.
The error message is fairly self-explanatory
(a,b,c,d,e) = line.split()
expects line.split() to yield 5 elements, but in your case, it is only yielding 1 element. This could be because the data is not in the format you expect, a rogue malformed line, or maybe an empty line - there's no way to know.
To see what line is causing the issue, you could add some debug statements like this:
if len(line.split()) != 11:
print line
As Martin suggests, you might also be splitting on the wrong delimiter.
Looks like something is wrong with your data, it isn't in the format you are expecting. It could be a new line character or a blank space in the data that is tinkering with your code.
I have a task where I need to record peoples scores in a text file. My Idea was to set it out like this:
Jon: 4, 1, 3
Simon: 1, 3, 6
This has the name they inputted along with their 3 last scores (Only 3 should be recorded).
Now for my question; Can anyone point me in the right direction to do this? Im not asking for you to write my code for me, Im simply asking for some tips.
Thanks.
Edit: Im guessing it would look something like this: I dont know how I'd add scores after their first though like above.
def File():
score = str(Name) + ": " + str(correct)
File = open('Test.txt', 'w+')
File.write(score)
File.close()
Name = input("Name: ")
correct = input("Number: ")
File()
You could use pandas to_csv() function and store your data in a dictionary. It will be much easier than creating your own format.
from pandas import DataFrame, read_csv
import pandas as pd
def tfile(names):
df = DataFrame(data = names, columns = names.keys())
with open('directory','w') as f:
f.write(df.to_string(index=False, header=True))
names = {}
for i in xrange(num_people):
name = input('Name: ')
if name not in names:
names[name] = []
for j in xrange(3):
score = input('Score: ')
names[name].append(score)
tfile(names)
Simon Jon
1 4
3 1
6 3
This should meet your text requirement now. It converts it to a string and then writes the string to the .txt file. If you need to read it back in you can use pandas read_table(). Here's a link if you want to read about it.
Since you are not asking for the exact code, here is an idea and some pointers
Collect the last three scores per person in a list variable called last_three
do something like:
",".join(last_three) #this gives you the format 4,1,3 etc
write to file an entry such as
name + ":" + ",".join(last_three)
You'll need to do this for each "line" you process
I'd recommend using with clause to open the file in write mode and process your data (as opposed to just an "open" clause) since with handles try/except/finally problems of opening/closing file handles...So...
with open(my_file_path, "w") as f:
for x in my_formatted_data:
#assuming x is a list of two elements name and last_three elems (example: [Harry, [1,4,5]])
name, last_three = x
f.write(name + ":" + ",".join(last_three))
f.write("\n")# a new line
In this way you don't really need to open/close file as with clause takes care of it for you
I'm not going to lie. I'm trying to do an assignment and I'm being beaten by it.
I need to have python prompt the user to enter a room number, then lookup that room number in a supplied .txt file which has csv [comma-separated values], and then show multiple results if there are any.
I was able to get python to return the first result ok, but then it stops. I got around the csv thing by using a hash command and .split (I would rather read it as a csv although I couldn't get it to work.) I had to edit the external file so instad of the data being seperated by commas it was seperated by semicolons, which is not ideal as I am not supposed to be messing with the supplied file.
Anyhow...
My external file looks like this:
roombookings.txt
6-3-07;L1;MSW001;1
6-3-07;L2;MSP201;1
6-3-07;L3;WEB201;1
6-3-07;L4;WEB101;1
6-3-07;L5;WEB101;1
7-3-07;L1;MSW001;2
7-3-07;L2;MSP201;2
7-3-07;L3;WEB201;2
7-3-07;L4;WEB101;2
7-3-07;L5;WEB101;2
8-3-07;L1;WEB101;1
8-3-07;L2;MSP201;3
Here's what my code looks like:
roomNumber = (input("Enter the room number: "))
def find_details(id2find):
rb_text = open('roombookings.txt', 'r')
each_line = rb_text.readline()
while each_line != '':
s = {}
(s['Date'], s['Room'], s['Course'], s['Stage']) = each_line.split(";")
if id2find == (s['Room']):
rb_text.close()
return(s)
each_line = rb_text.readline()
rb_text.close()
room = find_details(roomNumber)
if room:
print("Date: " + room['Date'])
print("Room: " + room['Room'])
print("Course: " + room['Course'])
print("Stage: " + room['Stage'])
If i run the program, I get prompted for a room number. If I enter, say, "L1"
I get:
Date: 6-3-07
Room: L1
Course: MSW001
Stage: 1
I should get 3 positive matches. I guess my loop is broken? Please help me save my sanity!
Edit. I've tried the solutions here but keeps either crashing the program (I guess I'm not closing the file properly?) or giving me errors. I've seriously been trying to sort this for 2 days and keep in mind I'm at a VERY basic level. I've read multiple textbooks and done many Google searches but it's all still beyond me, I'm afraid. I appreciate the assistance though.
Your code does "return(s)" the first time the "id2find" argument is exactly equal to the room.
If you want multiple matches, you could create an empty list before entering the loop, append every match to the list WITHOUT returning, return the list, and then use a for-loop to print out each match.
First. For iterating over lines in the file use next:
for line in rb_text:
# do something
Second. Your function returns after first match. How can it match more then one record? Maybe you need something like:
def find_details(id2find):
rb_text = open('roombookings.txt', 'r')
for line in rb_text:
s = {}
(s['Date'], s['Room'], s['Course'], s['Stage']) = line.split(";")
if id2find == (s['Room']):
yield s
rb_text.close()
And then:
for room in find_details(roomNumber):
print("Date: " + room['Date'])
print("Room: " + room['Room'])
print("Course: " + room['Course'])
print("Stage: " + room['Stage'])
And yes, you better use some CSV parser.
Your problem is the return(s) in find_details(). As soon as you have found an entry, you are leaving the function. You do not even close the file then. One solution is to use an empty list at the beginning, e.g results = [], and then append all entries which matches your requirements (results.append(s)).