如何将从迭代行中提取的子字符串连接成一个字符串?非常感谢您的帮助。
假设我有文件text.txt
One is 1
Two is 2
Three is 3
我想从该文件中提取单个字符串“ 1、2、3” 我可能错误地尝试了line.replace()和rstrip(),但两者均未提供所需的输出。我的代码如下所示。
def getnum():
with open("text.txt", "r") as f:
for line in f:
line.replace("\n", ",")
col=line.split(" is ")
num=col[0]
print(num)
f.close()
return
def getnum2():
with open("text.txt", "r") as f:
for line in f:
col=line.split(" is ")
num=col[0] + ","
num.rstrip("\n")
print(num)
f.close()
return
if __name__ == "__main__":
#getnum()
getnum2()
尝试第一个功能时得到的实际结果是
One
Two
Three
尝试第二个功能时得到的实际结果是
One,
Two,
Three,
答案 0 :(得分:0)
如果文件大小不大,并且您想将所需的单词存储在列表中,则可以将它们加入为:
def getnum():
with open("text.txt", "r") as f:
word_list = []
for line in f:
col = line.split(" is ")
word_list.append(col[0])
print((", ").join(word_list))
或者您可以使用以下方法在读取文件时进行打印:
对于python2:
def getnum():
with open("text.txt", "r") as f:
flag = False
for line in f:
if flag:
print ",",
flag = True
col=line.split(" is ")
num=col[0]
print num,
f.close()
return
对于python3:
def getnum():
with open("text.txt", "r") as f:
flag = False
for line in f:
if flag:
print (",", end=" ")
flag = True
col=line.split(" is ")
num=col[0]
print (num, end="")
f.close()
return