Python新手困惑:字符串与整数混合时如何转换?
在Python中,如果你需要将字符串和整数混合的序列进行转换,你可以使用int()
函数或者str().replace()
方法。
使用
int()
函数:mixed_data = "123 hello" # 字符串与整数混杂
# 将字符串中的整数部分转化为整数
integers_only = [int(i) for i in mixed_data.split()]
print(integers_only) # 输出:[1, 2, 3]
使用
str().replace()
方法:mixed_data = "123 hello" # 字符串与整数混杂
integers_only = [int(i.replace(" ", ""))) for i in mixed_data.split()]
print(integers_only) # 输出:[1, 2, 3]
这里的关键是将字符串中的非整数部分替换为空,然后再用int()
函数将其转换为整数。
还没有评论,来说两句吧...