我正在尝试打印包含大写和小写字母,数字和符号的随机字符串。这是我的代码:
genpassword = ''.join([random.choice(string.ascii_letters
+ string.digits
+ string.punctuation)
for n in range(12)])
到目前为止它的确有效。但是,我希望程序只打印特定的符号,如下所示:
symbols = ["!","$","%","^","&","*","(",")","-","_","=","+"]
string.punctuation 会打印所有这些符号,但会显示其他符号。
那么如何让我的程序生成一个只包含上面列表中的符号的字符串?
答案 0 :(得分:1)
您可以将所需的所有字符放入字符串中,然后使用它代替 void ControlRandomWander()
{
float pointDist = Vector3.Distance(currentWanderPos, transform.position);
if(pointDist < 2f || currentWanderPos == Vector3.zero)
{
wanderWaitTimer += Time.deltaTime * 15;
anims.LookAround(true);
if (wanderWaitTimer >= wanderWaitTime)
{
Vector3 randPos = GetRandomPositionAroundTarget(transform.position, -wanderRadius, wanderRadius);
NavMeshPath pth = new NavMeshPath();
NavMesh.CalculatePath(transform.position, randPos, agent.areaMask, pth);
float pathDist = 0f;
if (pth.status == NavMeshPathStatus.PathComplete)
{
for (int i = 0; i < pth.corners.Length - 1; i++)
{
pathDist += Vector3.Distance(pth.corners[i], pth.corners[i + 1]);
}
Debug.Log(pathDist);
if (pathDist <= wanderRadius)
{
currentWanderPos = randPos;
wanderWaitTime = Random.Range(wanderWaitMin, wanderWaitMax);
anims.LookAround(false);
wanderWaitTimer = 0;
MoveToPosition(randPos, true);
}
}
}
}
else
{
if (agent.destination != currentWanderPos)
{
MoveToPosition(currentWanderPos, true);
}
}
}
Vector3 GetRandomPositionAroundTarget(Vector3 pos, float minRange, float maxRange)
{
float offsetX = Random.Range(minRange, maxRange);
float offsetZ = Random.Range(minRange, maxRange);
Vector3 orgPos = pos;
orgPos.x += offsetX;
orgPos.z += offsetZ;
NavMeshHit hit;
if(NavMesh.SamplePosition(orgPos, out hit, 5f, agent.areaMask))
{
Debug.Log(hit.position);
return hit.position;
}
Debug.Log(hit.position);
return pos;
}
:
string.punctuation
这实际上是你的代码已经运行的方式,例如symbols = "!$%^&*()-_=+"
genpassword = ''.join([random.choice(string.ascii_letters + string.digits + symbols ) for n in range(12)])
也只是一个字符串,请参阅Python解释器(一种很好的实验方法):
string.ascii_letters