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}'
Related
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")
This question already has answers here:
How to format list in python
(3 answers)
Print list without brackets in a single row
(14 answers)
How to print a list without brackets and commas
(3 answers)
Closed 1 year ago.
I wrote this code:
#client.command()
async def getinfo(ctx, name):
url = f'https://api.mojang.com/users/profiles/minecraft/{name}'
response = requests.get(url)
uuid = response.json()['id']
url2 = f'https://api.hypixel.net/player?key=885e4c42-24d4-443a-93a8-ff25483cd6cc&uuid={uuid}'
response2 = requests.get(url2)
# END POINTS #
getuser = response2.json()['player']['displayname']
getpastuser = response2.json()['player']['knownAliases']
###########
await ctx.send(f'Username: {getuser}\nPast Usernames: {getpastuser}')
This outputs
Username: 35days
Past Usernames: ['UsernameIsntUsed', 'hqcc', '35days']
How can I get rid of the brackets and mini-quotes around the Past usernames part? I have no clue how to do it. I have looked around and tried many methods and nothing seems to work.
Follow this example I think you will get clear concept and easily will solve your issue.
apples = ["Fuji", "McIntosh", "Red Delicious", "Gala", "Jonagold"]
separator = ", "
print(separator.join(apples))
Use join on the list... in the event that there other types in the list other than string than cast it to string (may not be necessary)
with casting:
getpastuser = response2.json()['player']['knownAliases']
getpastuserstr = ', '.join(str(e) for e in getpastuser)
await ctx.send(f'Username: {getuser}\nPast Usernames: {getpastuserstr}')
without:
getpastuser = response2.json()['player']['knownAliases']
getpastuserstr = ', '.join(getpastuser)
await ctx.send(f'Username: {getuser}\nPast Usernames: {getpastuserstr}')
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'")
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)
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"