我有一个字符串,看起来像“ABC DEF GHI”,我希望能够创建一个只有“ABC”或“DEF”或“GHI”的新字符串。我试图使用.isalpha方法来确定字符串何时从字母变成空格。这就是我的代码的样子:
def get_word(chars: str, width: int) -> str:
word = ""
for i in range(len(chars)):
if chars[i].isaplpha():
word += chars[i]
if chars[i].isspace():
break
return word
但是,我得到一个未解决的属性引用错误,因为我的输入需要是字符串。这是什么意思?它不允许我使用。isalpha。但是如果i=1,那么chars[i]=“B”是字母顺序,所以我很困惑
我不允许使用拆分方法。。。请帮忙
您可以在递归中使用^{} 或^{} ,如以下示例所示:
使用
str.partition()
:使用
str.find()
:测试:
输出:
性能比较:
如果您正在寻找此问题的通用解决方案,可以使用正则表达式:
这将检索3个连续大写字母字符(A到Z)的所有实例
如果输入字符串还可以包括数字,如“AB3 DEF 2HI”,那么您也可以使用
output = re.findall('\w{3}', a)
如果输入字符串具有不同长度的“字”,则可以使用
output = re.findall('\w+', a)
,它将匹配任意数量的连续字符要了解有关regex的更多信息,并亲自使用它,可以使用regexr.com
对于这类问题,您可能需要一个正则表达式
相关问题 更多 >
编程相关推荐