Skip to main content
 首页 » 编程设计

python之疯狂的字符串连接

2025年05月04日17exmyth

我正在尝试将 .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 输入?

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

newline characters in the strings received

解决办法:看答案

请您参考如下方法:

你应该改变

print item + str(i) 

到

print item.rstrip() + str(i) 

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


一些其他提示:

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

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

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

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