简体   繁体   English

从变量中删除空格/逗号以添加到字符串

[英]remove spaces/commas from a variable to add to a string

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(','))
  1. strip only strips from the beginning and end of the string, it doesn't strip the characters from the middle. strip只从字符串的开头和结尾剥离,它不会从中间剥离字符。
  2. Your problem isn't really stripping, it's adding unnecessary junk in the first place by directly stringifying the tuple .您的问题并不是真正的剥离,而是通过直接对tuple字符串化来首先添加不必要的垃圾。

To fix both, convert trypass to a string up front with no joiner characters in the middle:要解决这两个问题, trypasstrypass转换为中间没有连接字符的字符串:

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:旁注:您可以使用itertools.product将其缩短很多,将四个循环变成一个(无箭头形代码),并通过将range元素仅转换为str一次来避免重复字符串化,直接生成不带中间命名变量的trypass

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, eg (3, 3, 3, 3) . .format(trypass)将使用默认的元组格式规则将元组格式化为字符串,例如(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,或者,因为你知道正好有 4 个数字,

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.或者,直接迭代 4 位数字。 itertools.product can generate the tuples for you. itertools.product可以为您生成元组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM