Python 2.7 - IPython 'raw_input' 并附加到列表 - 在每个项目之前添加 'u'

标签 python list python-2.7 ipython

我在 Mac OSX Lion 上使用 Python 2.7。我将 IPythonPandas 0.11.0NumpyStatsmodels 包一起使用。

我正在编写一个函数,允许用户对文件进行逻辑回归,指定在构建模型时使用哪些变量,哪些变量应该转换为虚拟变量以及哪个变量应该是自变量。

例如,当我执行以下操作时:

 cols_to_keep = []
 print (df.columns)
 i = eval(raw_input('How many of these variables would you like to use in logistic regression?: '))
 while i != 0:
    i = i - 1
    print (df.columns)
    addTo = raw_input('Enter a variable for this list that you would like to keep and use in logistic regression.: ')
    cols_to_keep.append(addTo)

我最终遇到了问题。具体来说,当我要求用户从列表中指定因变量,然后需要将该变量从训练变量列表中取出时:

print (df.columns)

dependent = raw_input('Which of these columns would you like to be the dependent variable?: ')
training.remove(dependent)

我发现,插入打印语句后,添加到训练变量列表中的变量如下所示:

('these are the traing variables: ', ['access', u'age_age6574', u'age_age75plus', u'sex_male', u'stage_late', u'death_death'])

似乎在每个用户指定的变量之前放置了一个u

我的问题是:为什么会这样以及如何修复/解决此问题,以便当用户指定因变量时,它实际上会从列表中删除。这种情况也会发生在用户指定变量并将其添加到列表中的所有其他情况下,如果我需要用户观察列表,则会造成困惑。

最佳答案

这些只是 unicode 字符串,而不是字节字符串。没有什么问题,字符串的内容不受影响。 u'text' 只是为了让您在查看 repr 时能够区分 Python 2 中的字节字符串和 unicode 字符串。如果打印该字符串,您将看不到任何差异。在 Python 3 中情况正好相反,其中 "text" 表示 unicode 字符串,而 b"bytes" 表示字节字符串。

如果你真的想将它们强制转换为字节串(不太可能),你可以这样做:

def ensure_str(s):
    if isinstance(s, unicode):
        s = s.encode('utf-8')
    return s

s = ensure_str(raw_input("prompt >"))

关于Python 2.7 - IPython 'raw_input' 并附加到列表 - 在每个项目之前添加 'u',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17012908/

相关文章:

Python: "' str'不支持subprocess.communicate上的缓冲区接口(interface)(迁移到3.x)

python - MAC 上的 Selenium,消息 : 'chromedriver' executable may have wrong permissions

python - 我如何动态地(循环)在 google colab 中显示图像?

python - 如何检测两个 PIL 图像之间的运动? (包括 wxPython 网络摄像头集成示例)

javascript - 使用 dynatable 查询样式化列表

c# - 创建一个包含对象新实例的列表

python-3.x - Cython 编译器指令 language_level 不受尊重

python - GDB python API - 获取 gdb 的 python API 来打印有问题的行号

Python:将列表链接在一起

python - 在python中使用正则表达式匹配文件夹列表