python strip函数没有给出预期的输出 [英] python strip function is not giving expected output

查看:89
本文介绍了python strip函数没有给出预期的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,其中文件名是FR1.1.csv,FR2.0.csv等。我使用这些名称打印在标题行中,但我想将这些名称修改为FR1.1,Fr2.0和以此类推。因此,我正在使用Strip功能删除.csv。当我在命令提示符下尝试它时,它的工作正常。但是,当我将其添加到主脚本时,它没有给出输出。

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. Hence i am using strip function to remove .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');

我得到的输出

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

必需的输出->

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

我想for循环后我的代码中存在一些缩进问题。
plesae告诉我实现此目标的正确方法是什么。

i guess some indentation problem is there in my code after for loop. plesae tell me what is the correct way to achive this.

推荐答案

字符串是不可变的,因此字符串方法可以'要更改原始字符串,它们会返回一个新的字符串,您需要再次分配该字符串:

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!

但是此通话并没有达到您的预期。它将删除所有开头和结尾字符 c s v

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 . from your string:

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

您可能想做

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

这篇关于python strip函数没有给出预期的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆