无法在Python中使用“Strip”从字符串中删除字符串

2024-10-03 04:25:58 发布

您现在位置: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 

Tags: theto方法字符串代码fromandata
2条回答

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

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

相关问题 更多 >