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)
Related
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 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}'
This question already has answers here:
Find string between two substrings [duplicate]
(20 answers)
Closed 2 years ago.
If you were to have a string of characters/numbers in a sequence - say AACBDEFZZBGFAAFFGGCCEEZZ
How could you iterate over the string, and then have every character between the AA and ZZ appear in a list? The end result in this case being:
[CBDEF], [FFGGCCEE] ?
Thanks
You can use str.index:
def between_markers(s, starting_marker="AA", ending_marker="ZZ"):
# keep track of where the previous marker was found
prev_ind = 0
ret = []
while True:
try:
# find the starting marker
start = s.index(starting_marker, prev_ind) + len(starting_marker)
# find the ending marker
end = s.index(ending_marker, start)
prev_ind = end + len(ending_marker)
# slice and append to return list
ret.append(s[start:end])
except ValueError:
# couldn't find one of the two markers so we're done
break
return ret
between_markers("AACBDEFZZBGFAAFFGGCCEEZZ") # ['CBDEF', 'FFGGCCEE']
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"
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$