remove spaces/commas from a variable to add to a string - python

I need it to look like
https://doorpasscode.kringlecastle.com/checkpass.php?i= (3333)&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c
instead it looks like
https://doorpasscode.kringlecastle.com/checkpass.php?i= (3, 3, 3, 3)&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c
Code:
for i in range(0, 4):
for j in range(0, 4):
for k in range(0, 4):
for l in range(0, 4):
trypass=(i,j,k,l)
#print(i,j,k,l, sep='')
print('https://doorpasscode.kringlecastle.com/checkpass.php?i= {}&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(trypass).strip(','))

strip only strips from the beginning and end of the string, it doesn't strip the characters from the middle.
Your problem isn't really stripping, it's adding unnecessary junk in the first place by directly stringifying the tuple.
To fix both, convert trypass to a string up front with no joiner characters in the middle:
trypass = ''.join(map(str, (i,j,k,l)))
A side-note: You could shorten this a lot with itertools.product to turn four loops into one (no arrow shaped code), and avoid repeatedly stringifying by converting the range elements to str only once, directly generating trypass without the intermediate named variables:
from itertools import product
for trypass in map(''.join, product(map(str, range(0, 4)), repeat=4)):
print('https://doorpasscode.kringlecastle.com/checkpass.php?i= ({})&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(trypass).)

.format(trypass) will format the tuple as a string using the default tuple formatting rules, e.g. (3, 3, 3, 3). Instead you should explicitly tell it how to format the string, like:
.format(''.join(str(i) for i in trypass))

You have a tuple that you want to reduce to a string.
>>> trypass = (3,3,3,3)
>>> ''.join(str(i) for i in trypass)
'3333'
Or, since you know there are exactly 4 digits,
print('https://doorpasscode.kringlecastle.com/checkpass.php?i={}{}{}{}&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(*trypass))
Or, just iterate over the 4-digit numbers directly. itertools.product can generate the tuples for you.
import itertools
for trypass in itertools.product("0123", repeat=4):
print('https://doorpasscode.kringlecastle.com/checkpass.php?i={}{}{}{}&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(*trypass))

Related

Remove spaces from a list of integers

I wrote a code that accepts multiple numbers and converts them into a list of integers. But I get them with spaces.
For example: I enter as input: 1,2,3,4,5 (with commas).
I get a list of [1, 2, 3, 4, 5]
Now I just need to delete the spaces but It's not working, I need it to look something like this [1,2,3,4,5].
I tried doing it this way:
numbers = input().split(',')
for i in range(0, len(numbers)):
numbers[i] = int(numbers[i])
mylist = str(numbers).replace(' ','')
print(mylist)
This causes the square parentheses to be considered as items.
How do I delete the spaces the right way?
I think you are conflating the list and the representation of the list. The list itself doesn't have spaces, or even commas, it just has the items (in your case, the numbers). The representation of the list is just that - a way to represent the data inside of it in a normal, standard way. That standard includes commas and spaces.
If you want a new thing that represents the list and its items in the way you are saying, you can do that by making a new string just like that.
str(numbers).replace(' ','')
This has two functions in it, chained together. First, we do str(numbers) to get a string that is the string-representation of the list. This will be the string '[1, 2, 3, 4, 5]'. Then you replace any blank space-bar ' ' with nothing ''.
Edit:
I think I read your question too quickly and see that you did the exact same as what I have in my code here and said it isn't doing exactly what you want to do. I think the answer here is: no.
As I say in my first paragraph, there is the list and there is the lists representation. The function for the list's representation is a python built-in that can not be trivially overridden. I'm not saying it can't be done, but I don't think you'll get it done without defining some new things.
You can change the print behavior of the list to something you code yourself.
numbers = input().split(',')
for i in range(0, len(numbers)):
numbers[i] = int(numbers[i])
mylist = str(numbers).replace(' ','')
print('[' + ','.join([str(n) for n in numbers]) + ']')
This prints a bracket [, then each number separated by commas without any spaces, and finally the ending bracket ].
Output looks like this:
1, 2, 3, 4, 5
[1,2,3,4,5]
My understanding of your problem is that you want to input a list as a string and want to transform it into a Python list of numbers.
If you input the following string [1, 2, 3, 4, 5], then you can split on , . Then you need to consider removing the leftmost and rightmost character, that correspond to the brackets:
numbers = input()[1:-1].split(', ')
for i in range(len(numbers)):
numbers[i] = int(numbers[i])
print(numbers)
Other options to transform the numbers from strings to integers are the following:
Python built-in map function:
numbers = input()[1:-1].split(', ')
numbers = list(map(int, numbers))
print(numbers)
Python list comprehension:
numbers = input()[1:-1].split(', ')
numbers = [int(n) for n in numbers]
print(numbers)
What you might want to do is create a subclass of list that has the repr implementation you want. That way you can still operate on your list object as you would any other list (e.g. you can access numbers[0] and it will return the first number), but printing the list as a whole will produce the output you're looking for.
class MyList(list):
def __repr__(self) -> str:
return "[" + ",".join(repr(i) for i in self) + "]"
numbers = MyList(int(n) for n in input().split(","))
print(numbers)
print(numbers[0])
Input:
1,2,3,4,5
Output:
[1,2,3,4,5]
1
Since MyList is a list subclass, you can construct one from any iterable, including a generator expression (as in the code above) or an existing list, e.g.:
>>> n_copy = MyList(numbers)
>>> n_copy
[1,2,3,4,5]
You could use the re module's split function to deal with the whitespaces when splitting. Then you just need to join the elements with ',' and embed the whole thing between brackets in the string representation.
import re
numbers = re.split(r'\s*,\s*', input())
print(f"[{','.join(numbers)}]")

Loop inside an f-string as a value for an embed

I have a tuple with some values and I want to send them in an embed. They're inside a dictionary like this
dict = {key: [(1, 2, 3), other values here], other key: [(1, 2, 3, 4, 5), other values here]}
Now some of the tuples here are of different lengths and it triggers me if I used a loop to add an embed field since discord doesn't allow the name parameter to be false or null yet. If I use a 0 width whitespace character, there's a big space that I'd rather not have. Tried using ternary operators but it didn't work. I also can't have this
for i in range(0, len(dict) - 1): pass
since the loop would've already came to an end before I could use it to index the tuple. I also tried doing
value = f'{tuple[i] for i in range(0, len(tuple) - 1)}'
but the bot return <generator object stats.<locals>.<genexpr> at 0x0000012E94AB3200> instead of the values inside the tuple.
Edit:
Thanks to the people who answered! It now works, thanks
tuple[i] for i in range(0, len(tuple) - 1)
Is a generator expression, it doesn't produce any values unless consumed by something like a loop or list()
You can use the equivalent list-comprehension instead:
f'{[tuple[i] for i in range(0, len(tuple) - 1)]}'
Or put the generator inside a list()
f'{list(tuple[i] for i in range(0, len(tuple) - 1))}'
Because your comprehension is not wrapped in [] it is technically a generator expression () (I think this would have worked in python 2.7 though), try this:
my_tuple = (1, 2, 3, 4)
f'{[my_tuple[i] for i in range(0, len(my_tuple) - 1)]}'
Output:
[1, 2, 3]
Also, there are no tuple comprehensions in python because tuples are immutable.

Manipulating the list of tuples in Python

I have a 2-element list like:
[(2, u'0.267*"sugar" + 0.266*"bad"'), (0, u'0.222*"father" + 0.222*"likes"')]
I want to get the first words of tuples that is I want to get a 2-element list as:
["sugar","father"]
I don't know how can I achive this since I am unfamilier with u' notation. Can anyone help or give some hints?
Using str methods
Ex:
d = [(2, u'0.267*"sugar" + 0.266*"bad"'), (0, u'0.222*"father" + 0.222*"likes"')]
print([i[1].split("+")[0].split("*")[1].replace('"', "").strip() for i in d])
Output:
[u'sugar', u'father']
str.split to split string by ("+" and "*")
str.replace to replace extra quotes
str.strip to remove all trailing or leading space.
You can find the value of an index location using square brackets.
myList[index]
In nested lists:
myList[indexInOuterList][indexInInnerList]
For your situation:
myList[indexInList][indexInTuple]
mylist = [(2, u'0.267*"sugar" + 0.266*"bad"'), (0, u'0.222*"father" + 0.222*"likes"')]
myList[0][0] #This is the integer 2

string multi index replace without affecting the insert order?

Suppose I have a string value str=xxx. Now I want to replace it via multi-index, such as {(1, 3):'rep1', (4, 7):'rep2', (8, 9):'rep3'}, without disturbing the index order. How can I do it?
Pseudo-code (in Python 2.7):
str = 'abcdefghij'
replacement = {(1, 3):'123', (4, 7):'+', (8, 9):'&'} # right index isn't include
# after some replacements:
str = some_replace(str, replacement)
# i want to get this:
print str
# 'a123d+h&j'
# since string is immutable, make a list out of the string to modify in-place
lst = list(str)
Use slice to modify items, a stronger explanation about slice and assignment can be found here; slice(*k) creates a slice object from the keys of the replacement. For instance, slice(*(1, 3)) gives a slice of slice(1, 3) which is equivalent to lst[1:3] when used as index, and replaces the corresponding elements with the corresponding value when the assignment on the slice is called:
# Here sort the index in reverse order so as to avoid tracking the index change due to the
# difference of the sizes between the index and replacement
for k, v in sorted(replacement.items(), reverse=True):
lst[slice(*k)] = v
''.join(lst)
# 'a123d+h&j'

new line with variable in python

When I use "\n" in my print function it gives me a syntax error in the following code
from itertools import combinations
a=[comb for comb in combinations(range(1,96+1),7) if sum(comb) == 42]
print (a "\n")
Is there any way to add new line in each combination?
The print function already adds a newline for you, so if you just want to print followed by a newline, do (parens mandatory since this is Python 3):
print(a)
If the goal is to print the elements of a each separated by newlines, you can either loop explicitly:
for x in a:
print(x)
or abuse star unpacking to do it as a single statement, using sep to split outputs to different lines:
print(*a, sep="\n")
If you want a blank line between outputs, not just a line break, add end="\n\n" to the first two, or change sep to sep="\n\n" for the final option.
Two possibilities:
print "%s\n" %a
print a, "\n"
This will work for you:
I used 1,2...6 in my example and 2 length tuples with a combination sum of 7.
from itertools import combinations
a=["{0}\n".format(comb) for comb in combinations(range(1,7),2) if sum(comb) == 7]
print(a)
for thing in a:
print(thing)
Output
['(1, 6)\n', '(2, 5)\n', '(3, 4)\n']
(1, 6)
(2, 5)
(3, 4)
for me in the past something like print("\n",a) works.

Categories