for循环中的空变量

时间:2019-01-22 21:48:31

标签: python python-3.x for-loop random

我有这种单线笔,效果很好。

function isInRange(checkRange, targetCell) {
  //--- check the target cell's row and column against the given
  //    checkrange area and return True if the target cell is
  //    inside that range
  var targetRow = targetCell.getRow();
  if (targetRow < checkRange.getRow() || targetRow > checkRange.getLastRow()) return false;

  var targetColumn = targetCell.getColumn();
  if (targetColumn < checkRange.getColumn() || targetColumn > checkRange.getLastColumn()) return false;

  //--- the target cell is in the range!
  return true;
}

function onEdit(eventObj) {
  //--- you could set up a dynamic named range for this area to make it easier
  var thisSheet = SpreadsheetApp.getActiveSheet();
  var checkRange = thisSheet.getRange("F2:F200");  
  if (isInRange(checkRange, eventObj.range)) {
    //--- so one of the checkboxes has changed its value, so hide or show
    //    that row
    var checkbox = eventObj.range;
    var rowIndex = checkbox.getRow();
    Logger.log('detected change in checkbox at ' + checkbox.getA1Notation() + ', value is now ' + checkbox.getValue());
    if (checkbox.getValue() == true) {
      Logger.log('hiding the row');
      thisSheet.hideRows(rowIndex, 1);
    } else {
      Logger.log('showing the row');
      thisSheet.showRows(rowIndex, 1);
    }
  }
}

我现在想将其转换为“正常”的for循环。

import random
from string import ascii_letters, digits

def pwd_generator(pwd):

    password = "".join([random.choice(ascii_letters + digits) for i in range(pwd)])
    print(password)

在这种情况下,def pwd_generator(pwd): password = '' for i in range(pwd): password.join([random.choice(ascii_letters + digits)]) print(password) 为空。

当我尝试在“适当的” for循环中写入变量时,为什么变量为空?

1 个答案:

答案 0 :(得分:2)

字符串是不可变的,因此password.join返回一个字符串,但不会将其保存为密码。相反,您应该将字符串保存在列表中,并在最后加入它们:

password = []
for i in range(pwd):
    password.append(random.choice(ascii_letters + digits)

return "".join(password)