繁体   English   中英

无法使用 Python 中的“Strip”从字符串中消除字符串

[英]Unable to eliminate a string of characters from a String using “Strip” in Python

我使用以下方法从字符串中删除了某个尾随字符串“lbs”。 但是,当我运行我的代码并打印出结果时,什么都没有改变,字符串也没有被消除。 非常感谢您在这种情况下的帮助! 谢谢您的帮助!

Data:
**Weights:**
0        159lbs
1        183lbs
2        150lbs
3        168lbs
4        154lbs

**Code:**
# Converting the Weights to an Integer Value from a String
for x in Weights:
    if (type(x) == str):
        x.strip('lbs')

**Output:**    
Weights:
0        159lbs
1        183lbs
2        150lbs
3        168lbs
4        154lbs 

您正在从字符串中剥离值,但没有将其保存在列表中。 尝试使用数字索引,如下所示:

Weights = ['159lbs', '183lbs', '150lbs', '168lbs', '154lbs']

# Converting the Weights to an Integer Value from a String
for x in range(len(Weights)):
    if (type(Weights[x]) == str):
        Weights[x] = Weights[x].strip('lbs')

但是,如果您不习惯使用范围循环,则可以按如下方式枚举:

Weights = ['159lbs', '183lbs', '150lbs', '168lbs', '154lbs']

# Converting the Weights to an Integer Value from a String
for i, x in enumerate(Weights):
    if (type(x) == str):
        Weights[i] = x.strip('lbs')

这对你有帮助吗..?

在这里,我没有使用isinstance(line, str)来明确检查该行是否为string ,因为行号是integer (我想)。

with open('Data.txt', 'r') as dataFile:
    dataFile.readline()
    for line in dataFile.readlines():
        number, value = line.strip().split()
        print(value.strip('lbs'))

159
183
150
168
154

在这里,我将数据放入 txt 文件中:

**Weights:**
0        159lbs
1        183lbs
2        150lbs
3        168lbs
4        154lbs

暂无
暂无

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

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