简体   繁体   English

python strip函数没有给出预期的输出

[英]python strip function is not giving expected output

i have below code in which filenames are FR1.1.csv, FR2.0.csv etc. I am using these names to print in header row but i want to modify these name to FR1.1 , Fr2.0 and so on. 我有下面的代码,其中文件名是FR1.1.csv,FR2.0.csv等。我使用这些名称在标题行中打印,但我想将这些名称修改为FR1.1,Fr2.0等。 Hence i am using strip function to remove .csv. 因此我使用strip函数删除.csv。 when i have tried it at command prompt its working fine. 当我在命令提示符下尝试它的工作正常。 But when i have added it to main script its not giving output. 但是当我把它添加到主脚本时它没有给出输出。

for fname in filenames:
    print "fname     : ", fname
    fname.strip('.csv');
    print "after strip fname: ", fname
    headerline.append(fname+' Compile');
    headerline.append(fname+' Run');

output i am getting 输出我得到了

fname     :FR1.1.csv
after strip fname: FR1.1.csv

required output--> 要求输出 - >

fname     :FR1.1.csv
after strip fname: FR1.1

i guess some indentation problem is there in my code after for loop. 我想在for循环后我的代码中有一些缩进问题。 plesae tell me what is the correct way to achive this. plesae告诉我实现这个的正确方法是什么。

Strings are immutable, so string methods can't change the original string, they return a new one which you need to assign again: 字符串是不可变的,因此字符串方法不能更改原始字符串,它们返回一个您需要再次分配的新字符串:

fname = fname.strip('.csv')   # no semicolons in Python!

But this call doesn't do what you probably expect it to. 但是这个电话没有做你想象的那样。 It will remove all the leading and trailing characters c , s , v and . 它将删除所有前导和尾随字符csv. from your string: 来自你的字符串:

>>> "cross.csv".strip(".csv")
'ro'

So you probably want to do 所以你可能想做

import re
fname = re.sub(r"\.csv$", "", fname)

Strings are immutable. 字符串是不可变的。 strip() returns a new string. strip()返回一个新字符串。

>>> "FR1.1.csv".strip('.csv')
'FR1.1'
>>> m = "FR1.1.csv".strip('.csv')
>>> print(m)
FR1.1

You need to do fname = fname.strip('.csv') . 你需要做fname = fname.strip('.csv')

And get rid of the semicolons in the end! 并最终摆脱分号!

PS - Please see Jon Clement's comment and Tim Pietzcker's answer to know why this code should not be used. PS - 请参阅Jon Clement的评论和Tim Pietzcker的答案,了解为何不应使用此代码。

You probably should use os.path for path manipulations: 您可能应该使用os.path进行路径操作:

import os

#...

for fname in filenames:
    print "fname     : ", fname
    fname = os.path.splitext(fname)[0]
    #...

The particular reason why your code fails is provided in other answers. 其他答案中提供了代码失败的特殊原因。

change 更改

fname.strip('.csv')

with

fname = fname.strip('.csv')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM