You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

报错“String object has no attribute 'str'”,求Python代码修复方案

错误原因与修复方案

错误原因

你代码里的x是普通Python字符串,而.str属性是Pandas Series/DataFrame对象才有的专属方法,普通字符串没有这个属性,所以触发了报错。

修复方法

情况1:仅处理单个普通字符串

直接用Python原生的in关键字判断是否包含目标词,搭配np.where使用:

import numpy as np

x = 'this string is supposed to contain windows'
result = np.where('windows' in x, 'Windows', 'Non Windows')

情况2:原本要处理Pandas序列(批量字符串场景)

如果你的需求是批量处理字符串,需要先把x转为Pandas Series对象,再使用.str.contains()方法:

import pandas as pd
import numpy as np

x = pd.Series(['this string is supposed to contain windows'])
result = np.where(x.str.contains('windows'), 'Windows', 'Non Windows')

内容的提问来源于stack exchange,提问作者M4RCUS.ERYX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 08:10:29