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

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"

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")

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'")

Injecting a variable inside a string, in a specific location [duplicate]

This question already has answers here:
How to print like printf in Python3?
(10 answers)
Closed 1 year ago.
I have this line:
assert response.headers['Content-Disposition'] == 'attachment; filename=myFile.txt'
In the second string of the line ('attachment; filename=myFile.txt')
I want to remove the hardcoded filename (myFile.txt) and replace it with a variable that i have.
Like printf() in C, in a way, replacing the string at that exact location with a variable.
You could use an f-string:
fileName = 'myFile.txt'
# ...
assert response.headers['Content-Disposition'] == f'attachment; filename={fileName}'

Convert set to list in Python [duplicate]

This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 3 years ago.
I'm converting a set to a list, and then to a string in Python. I can remove the brackets in the string output, but I also want to remove the quotes around the string.
This is what I tried:
instance_list = ec2.describe_instances()
for reservation in instance_list["Reservations"]:
for instance in reservation.get("Instances", []):
tree = objectpath.Tree(instance)
private_ips = set(tree.execute('$..PrivateIpAddress'))
if len(private_ips) == 0:
private_ips = None
if private_ips:
private_ips_list = list(private_ips)
private_ips_list = str(private_ips_list).replace('[','').replace(']','').replace('\','')
else:
public_ips_list = None
This is the error I get:
File ".\aws_ec2_list_instances.py", line 64
private_ips_list = str(private_ips_list).replace('[','').replace(']','').replace('\','')
^
SyntaxError: EOL while scanning string literal
If I change the bottom line to this, without the final replace, the script works.
private_ips_list = str(private_ips_list).replace('[','').replace(']','')
But the quotes are still there:
Private IP: '10.48.136.41'
How can I remove the quotes from the output?
you can do:
a = set(["Blah", "Hello"])
str1 = ''.join(a)

Put function outputs to a list in Python [duplicate]

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$

Categories