Put function outputs to a list in Python [duplicate] - python

This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
How to concatenate (join) items in a list to a single string
(11 answers)
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed 8 months ago.
The aim of the following program is to convert words in 4 characters from "This" to "T***", I have done the hard part getting that list and len working.
The problem is the program outputs the answer line by line, I wonder if there is anyway that I can store output back to a list and print it out as a whole sentence?
Thanks.
#Define function to translate imported list information
def translate(i):
if len(i) == 4: #Execute if the length of the text is 4
translate = i[0] + "***" #Return ***
return (translate)
else:
return (i) #Return original value
#User input sentense for translation
orgSent = input("Pleae enter a sentence:")
orgSent = orgSent.split (" ")
#Print lines
for i in orgSent:
print(translate(i))

On py 2.x you can add a , after print:
for i in orgSent:
print translate(i),
If you're on py 3.x, then try:
for i in orgSent:
print(translate(i),end=" ")
default value of end is a newline(\n), that's why each word gets printed on a new line.

Use a list comprehension and the join method:
translated = [translate(i) for i in orgSent]
print(' '.join(translated))
List comprehensions basically store the return values of functions in a list, exactly what you want. You could do something like this, for instance:
print([i**2 for i in range(5)])
# [0, 1, 4, 9, 16]
The map function could also be useful - it 'maps' a function to each element of an iterable. In Python 2, it returns a list. However in Python 3 (which I assume you're using) it returns a map object, which is also an iterable that you can pass into the join function.
translated = map(translate, orgSent)
The join method joins each element of the iterable inside the parentheses with the string before the .. For example:
lis = ['Hello', 'World!']
print(' '.join(lis))
# Hello World!
It's not limited to spaces, you could do something crazy like this:
print('foo'.join(lis))
# HellofooWorld!

sgeorge-mn:tmp sgeorge$ python s
Pleae enter a sentence:"my name is suku john george"
my n*** is s*** j*** george
You just need to print with ,. See last line of below pasted code part.
#Print lines
for i in orgSent:
print (translate(i)),
For your more understanding:
sgeorge-mn:~ sgeorge$ cat tmp.py
import sys
print "print without ending comma"
print "print without ending comma | ",
sys.stdout.write("print using sys.stdout.write ")
sgeorge-mn:~ sgeorge$ python tmp.py
print without ending comma
print without ending comma | print using sys.stdout.write sgeorge-mn:~ sgeorge$

Related

I'm trying to see how many lines start with a specific character I.E "0" but I'm not getting any results. Where did I go wrong the "startswith()"? [duplicate]

This question already has answers here:
How does python startswith work?
(2 answers)
Closed 5 months ago.
I'm learning how to manipulate strings in python. I'm currently having an issue using the "startswith()" function. I'm trying to see how many lines start with a specific character I.E "0" but I'm not getting any results. Where did I go wrong? The text file only contains random generated numbers.
random = open("output-onlinefiletools.txt","r")
r = random.read()
#print(len(r))
#small = r[60:79]
#print(r[60:79])
#print(len(r[60:79]))
#print(small)
for line in random:
line = line.rstrip()
if line.startswith(1):
print(line)
You are searching for 1 as an int, and I wouldn't use random as it is not protected but is generally used as part of the random lib; the lines are treated as strings once read thus you need to use startswith on a string and not an int.
myFile = open("C:\Dev\Docs\output-onlinefiletools.txt","r")
r = myFile.read()
# return all lines that start with 0
for line in r.splitlines():
if line.startswith("0"):
print(line)
Output:
00000
01123
0000
023478
startwith takes the prefix as argument, in your case it will be line.startswith("0")

Issue With Filter and sort a list Prompt - Python3 [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 1 year ago.
Below is the prompt I am having trouble with. I have come up with a solution that pretty much gets the proper output, but with an extra return/new line that should be a space and not a new line. Can anyone see what could be causing the new line?
Write a program that gets a list of integers from input, and outputs non-negative integers in ascending order (lowest to highest).
Ex: If the input is:
10 -7 4 39 -6 12 2
the output is:
2 4 10 12 39
For coding simplicity, follow every output value by a space. Do not end with new line.****
My Code:
#Get Input
user_input = input()
#Split input into individual entries within list
user_list = user_input.split()
map_object = map(int, user_list)
list_of_integers = list(map_object)
#Remove Negative Values from list
list_of_integers = [i for i in list_of_integers if i >= 0]
#Sort List In Ascending Order
list_of_integers.sort()
#Convert list of integers back into a string
list_of_integers = [str(int) for int in list_of_integers]
#Join string by a space
str_of_ints =" ".join(list_of_integers)
print(str_of_ints)
If you want to remove the newline from the print you can just do this
print(str_of_ints, end='') # end character is now empty not \n

I have a list of hashes and their occurrences. I want to get the number of occurrences (the number after the semicolon) [duplicate]

This question already has answers here:
How to check if a string is a substring of items in a list of strings
(18 answers)
Closed 1 year ago.
Here is my code. It gets a list of hashes, which are leaked. I want to check my password against it. What I want it to do, is to, when it finds it to throw me back the number of occurrences it has been leaked, if at all. How can this be accomplished?
For example sake, let's say our necessary hash happens to be the 2nd one and thus we want to extract the number 3.
What we have already is the hash infront of it. It is named "ending" as you can see in the code.
import hashlib
import requests
password = input("Enter password: ")
encoded_str = password.encode()
hash_obj = hashlib.sha1(encoded_str)
hashed = hash_obj.hexdigest().upper()
beginning = hashed[:5]
ending = hashed[5:].strip()
response = requests.get("https://api.pwnedpasswords.com/range/"+beginning)
output = response.text
listing = output.split()
print(listing)
output:
['0015711CF2308DD93DC449B888F9805B728:1', '0083F4473656452B43073DF2861FD289F63:3', '0DE17FB8EC56DD673FF3AF94BAB5029BFF2:1', '0DEC778F27B49DECF0E7C3B8AB2DD152990:15', '0E8EEF1620F095A7A26F679388A02EFEA4C:2', '0FD09EF75E6654D1E2FB5FC715A11331B6D:2', '11CFB41389B28F08B74A17851292D086922:1', '12A7DE6568963683AA7D21E3FBA1A1B5D39:1', '12B602E54A280622E21FC57607D70F9E3D6:4', '133B5AFB8798339FF1BF29DBBD068DFB556:2912', '13723F1F53E4468943870CA48E2093C0531:5', '139946DFB7AA0936F96DFB9B27931508AC3:1', '13AB10DBA939781F0416361A25024EF0D8C:4', '13E2A779A5F3F6C4BA21F23A5FB949DE347:2', '52CFB9745616A23A369EA5AD9D480DFE8E9:1', '52F07FB24866744C9E7D7460A04C143AAA3:2']
Our goal output:
3
try to use this code:
num = 0
for line in listing:
if ending in line:
num = line.split(':')[1]
break
else:
print("the 'ending' is not in 'listing'")

How to remove a substring separated by a space in Python? [duplicate]

This question already has answers here:
How do I split a string into a list of words?
(9 answers)
Closed 7 years ago.
I am tying to find sha1sum for an .img file and the original device. Here's the method for doing that and the output i'm getting.
Code:
def hashcalc(self, file_path):
cmd1 = ["gksudo","sha1sum",file_path]
cmd2 = ["gksudo","sha1sum","/dev/mmcblk0"]
proc1 = subprocess.check_output(cmd1)
proc2 = subprocess.check_output(cmd2)
print proc1
print proc2
OUTPUT:
1ba1a6bbd66c335633d53d9bfff7366936e2e0e3 /home/user/Project/2gb.img
1ba1a6bbd66c335633d53d9bfff7366936e2e0e3 /dev/mmcblk0
Now how do I remove the path '/home/.../2gb.img' and '/dev/mmcblk0'. I want to compare those values. But normal '==' will not work as it contains the path as well. How do i remove that path. Please help.
Try using split and then compare:
proc1.split()[0] == proc2.split()[0]
string.split(" ") will split the the string by space and returns a list.
proc1.split(" ") will return ["1ba1a6bbd66c335633d53d9bfff7366936e2e0e3","/home/user/Project/2gb.img"]
You can get the first value of the list which will return the required value.
proc1.split(" ")[0] == "1ba1a6bbd66c335633d53d9bfff7366936e2e0e3"

Trying to read in an external file into a dictionary [duplicate]

This question already has an answer here:
How to read in a file into a dictionary
(1 answer)
Closed 8 years ago.
OK I am trying to read in an external file into a dictionary however I am receiving some syntax errors. The clues which get read in then have to replace the letters which they pair with in the list of coded words
My code for reading into a dictionary and replacing the symbols is as follows.
d = {}
def read_clues(clues):
global d
with open("hey.txt") as f:
for line in f:
(key, val) = line[1], line[0]
d[key] = val
def replace_symbols(clues, words):
global d
for word in range(len(words)):
for key, value in d.items():
words[word] = words[word].replace(key, value)
In the main part of my program I have the code for calling the replace_symbols. However I am getting a syntax error after print key, in the last line. The code for this is shown below.
#REPLACES LETTERS
print("======== The clues have been replaced ===========")
replace_symbols(clues, words)
for key, value in d.items():
print key, value // This will print the symbols and letters
Assuming that hey.txt has the keys and values separated by a space, the following code should work:
def read_clues(clues):
global d
with open("hey.txt") as f:
for line in f:
stuff = line.split(" ") #split each line into parts
(key, val) = stuff[1], stuff[0]
d[key] = val
If the separator is other than a space, just include it as an argument to split().
There are some other problems in your code, but since you're asking about the syntax error, it's almost certainly this line:
print key, value // This will print the symbols and letters
First, // does not mean "comment" in Python, it means "integer division". So, you're asking it to divide value by This (which would probably raise a NameError, because it's unlikely you have anything named This in your code), and then including a bunch of other identifiers starting with will. A string of two identifiers in a row isn't valid syntax.
How do you write a comment in Python? Use #, not //:
print key, value # This will print the symbols and letters
Second, if you're using Python 3.x, print is a normal function, like anything else, so its arguments have to go in parentheses, like all of your other function calls. (And given the print call a few lines up, I'm willing to bet you are using Python 3.x.) Most likely you've copied this from some code for Python 2.x. There are some important differences between Python 2 and 3, which means that not all code for Python 2 can be copied and pasted into your Python 3. And this is one of the cases where it doesn't work. So:
print(key, value) # This will print the symbols and letters
But don't make that second change if you're using Python 2.x; otherwise, you'll just end up printing a tuple instead of two strings separated by a space. (For example, print 1, 2 prints 1 2, but print(1, 2) prints (1, 2).)

Categories