Discord Python Remove Quotes and Brackets [duplicate] - python

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

Related

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

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)

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"

Python - Outputting Lists [duplicate]

This question already has answers here:
Print and join statement in python
(3 answers)
Closed 7 years ago.
I am creating a program in python that genrates a random passwrod from inputs from the user. My code so far is:
from random import *
symbols = ['!','"','£','$','%','^','&','*','(',')','-','_','=','/','*','-','+','{','}','[',']',':',';','#','>','#','~','<',',','.','?']
rand1 = randint(0,32)
rand2 = randint(0,32)
fore = raw_input('Enter your forename')
sur = raw_input('Enter your Surname')
birth = raw_input('Enter you birth year')
password = symbols[rand1], fore[0:2], sur[0:3], birth[2:4], symbols[rand2]
print password
When the program outputs the password it looks like this:
('+', u'jo', u'smi', u'90', '/')
Is there anyway to get rid of the extra characters such as the parenthesis and the commas?
try print ''.join(password).
Have a look at the documentation here. This will join the tuple you created into a string.
Alternatively you could join the components directly into a string by using the + operator, as it is suggested by #pzp.
Have a look at this code example, which shows both possible ways.
password = symbols[rand1], fore[0:2], sur[0:3], birth[2:4], symbols[rand2]
should be
password = symbols[rand1] + fore[0:2] + sur[0:3] + birth[2:4] + symbols[rand2]

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