循环遍历python中的字符串列表

时间:2017-04-10 15:50:45

标签: python

我需要帮助我在高中的最后一个项目。

首先我将一些数字保存到.txt文件中,然后尝试阅读它们。但后来我得到了这个清单:

target = open("salary.txt", "r")
time = target.readlines()
for i in time:
    i.replace("\n", "", 1)

我需要一种方法来删除" \ n",以某种方式将其保存到新列表中,这样我就可以使它们成为整数而不是字符串。

以下是我的想法(salary.txt是保存数字的文件)

      #examined-evidence {
        z-index: 1000;
        position: absolute;
        left: 25%;
        top: 10%;
        width: 50%;
        height: 80%;
        background: dimGray;
        border: 1px solid #33ffff;
        padding: 0px;
        margin: 0px;
      }

      #examined-evidence.active {
        display: inline-block;
      }

      #examined-evidence #examined-evidence-details {
        background-color: #333333;
      }

      #examined-evidence #examined-evidence-details .heading {
        padding: 0px;
        float: left;
        display: inline-block;
      }

      #examined-evidence #examined-evidence-details .heading p {
        text-align: justify;
        padding: 3px 12px 3px 12px;
        display: inline-block;
        font-size: 0.75em;
        position: relative;
        width: 100%;
        color: white;
        margin: 0px;
      }

      #examined-evidence #examined-evidence-image {
        text-align: center;
        margin: 0px auto;
        height: 80%;
        width: auto;
      }

      #examined-evidence #examined-evidence-image img {
        height: 80%;
      }

      #examined-evidence-close-button {
        background-color: red;
        display: inline-block;
        float: right;
        height: 34px;
        width: 34px;
        padding: 0px;
        position: relative;
        margin: 0px 15px 10px 10px;
      }
      .clear {
        clear: both;
      }

2 个答案:

答案 0 :(得分:3)

您最后可以使用strip()删除换行符。

times = ['360\n', '330\n', '482\n']
int_times = [int(time.strip()) for time in times]
# [360, 330, 482]

但实际上,您不需要它,因为int("3\n")已经3

int_times = [int(time) for time in times]
# [360, 330, 482]

这意味着你也可以写:

int_times = map(int, times)

答案 1 :(得分:0)

我会这样做。

salaries = []
with open("salary.txt") as time:
    for i in time:
        salaries.append( int(i.strip()) )