我已经使用以下方法从字符串中删除了某个字符'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 发布于 2021-01-22 17:29:27
您正在从字符串中删除该值,但未将其保存在列表中。尝试使用数字索引,如下所示:
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')但是,如果您不习惯使用ranged循环,则可以按以下方式进行枚举:
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')发布于 2021-01-22 17:33:32
这对你有帮助吗?
在这里,我没有使用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 154lbshttps://stackoverflow.com/questions/65849898
复制相似问题