Python程序在一个新行上打印

2024-09-28 22:33:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个随机字母,数字和字符的文本文件。在打印过程中,我必须删除特殊字符,最后只使用字母数字字符。在

出于某种原因,我的程序正在打印:

Line read' ,,s.8,ymsw5w-86    
 '

' ,,s.8,ymsw5w-86

 '->' s8ymsw5w86 '

当文本应该只有2行,而不是4行。像这样:

^{pr2}$

我不明白怎么了。这是我的代码:

file1=open(textfile1,"r")

for line in file1:

    line2="".join(filter(str.isalnum,line))

    print("Line read","'",str(line),"'")

    print("'",str(line),"'->'",line2,"'")

谢谢。在


Tags: 程序read过程字母line数字字符file1
1条回答
网友
1楼 · 发布于 2024-09-28 22:33:20

文件中的每一行末尾都有一个换行符。如果你不想让它打印出来,就把它剥掉

print("Line read","'",str(line.strip()),"'")
print("'",str(line.strip()),"'->'",line2,"'")

^{pr2}$

使用f-strings:如果要在字符串中使用单引号,请将字符串括在双引号中,反之亦然

print(f"'{s1.strip()}'")
print(f"'{s2.strip()}'  > '{s3.strip()}'")


>>>  
',,s.8,ymsw5w-86'
',,s.8,ymsw5w-86'  > 's8ymsw5w86'
>>>

或者

s1 = ',,s.8,ymsw5w-86 \n'
s2 = "".join(filter(str.isalnum,s1))

print(f"Line read ... '{s1.strip()}'")
print(f"'{s1.strip()}'  > '{s2.strip()}'")

>>>
Line read ... ',,s.8,ymsw5w-86'
',,s.8,ymsw5w-86'  > 's8ymsw5w86'
>>>

相关问题 更多 >