【问题标题】:String concatenation acting crazy字符串连接表现得很疯狂
【发布时间】:2014-01-20 18:02:54
【问题描述】:

我正在尝试将 .txt 列表中的每个单词连接到字符串 eg{ 'word' + str(1) = 'word1' } 使用此代码:

def function(item):
  for i in range(2):
    print item + str(i)

with open('dump/test.txt') as f:
  for line in f:
    function(str(line))

我将只使用仅包含两个单词('this'、'that')的 txt 文件。 我得到的是:

this
0
this
1
that0
that1

我所期待的:

this0
this1
that0
that1

如果我只使用function('this')function('that'),它可以正常工作,但为什么它不适用于 txt 输入?

--- 编辑: 解决了,谢谢! 问题是由

引起的

收到的字符串中的换行符

解决方案:查看答案

【问题讨论】:

    标签: python concatenation string-concatenation


    【解决方案1】:

    你应该改变

    print item + str(i)
    

    print item.rstrip() + str(i)
    

    这将删除function 中收到的字符串中的所有换行符。


    其他几个提示:

    1. 打印数据的更好方法是使用.format 方法,例如在你的情况下:

      print '{}{}'.format(item.strip(), i)
      

      如果您有更复杂的任务,此方法非常灵活。

    2. 从文件中读取的所有行都是字符串 - 您不必对它们调用 str()

    【讨论】:

    • 我会更具体并使用item.rstrip('\n')
    【解决方案2】:

    python 读取的第一行是this\n,当您将01 附加到此时,您会得到this\n0this\n1。而如果在第二行中您在文件末尾没有新行(从您正在打印的内容推断)。所以附加对它来说很好。

    要从字符串的右端删除\n,您应该使用rstrip('\n')

    print (item.rstrip('\n') + str(i))
    

    【讨论】:

    • 我会更具体并使用item.rstrip('\n')
    【解决方案3】:

    在第一个“This\n”中,这就是您没有得到格式化输出的原因。删除新行字符后传递参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多