我一直在玩startswith(),我发现了一些有趣的东西:
>>> tup = ('1', '2', '3')
>>> lis = ['1', '2', '3', '4']
>>> '1'.startswith(tup)
True
>>> '1'.startswith(lis)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: startswith first arg must be str or a tuple of str, not list
Run Code Online (Sandbox Code Playgroud)
现在,错误是显而易见的,并将列表转换为元组将正常工作,就像它在第一时间做的那样:
>>> '1'.startswith(tuple(lis))
True
Run Code Online (Sandbox Code Playgroud)
现在,我的问题是:为什么第一个参数必须是str或str前缀的元组,而不是 str前缀列表?
AFAIK,Python代码startswith()可能如下所示:
def startswith(src, prefix):
return src[:len(prefix)] == prefix
Run Code Online (Sandbox Code Playgroud)
但这让我更加困惑,因为即使考虑到它,无论是列表还是元组,它仍然不应该有任何区别.我错过了什么?
我尝试使用 or 函数为同一输出输入多个单词,但它只将第一个单词作为输入,而不将其余单词作为输入。我该如何解决这个问题?谢谢!例如:
message.content.startswith("hi" or "hey")
Run Code Online (Sandbox Code Playgroud)
只接受“hi”作为输入,而不接受“hey”。
我尝试过将单词添加到列表中,但效果不佳。我对编码比较陌生,所以如果这是一个愚蠢的问题,我提前表示抱歉
我有一个词袋作为列表格式的元素。我正在尝试搜索这些单词中的每一个是否仅出现在 Pandas 数据框中,前提是它“以”列表中的元素开头。我尝试过“startswith”和“contains”来进行比较。
代码:
import pandas as pd
# list of words to search for
searchwords = ['harry','harry potter','secret garden']
# Data
l1 = [1, 2, 3,4,5]
l2 = ['Harry Potter is a great book',
'Harry Potter is very famous',
'I enjoyed reading Harry Potter series',
'LOTR is also a great book along',
'Have you read Secret Garden as well?'
]
df = pd.DataFrame({'id':l1,'text':l2})
df['text'] = df['text'].str.lower()
# Preview df:
id text
0 1 harry potter is a great book …Run Code Online (Sandbox Code Playgroud) 我的列表包含一些项目,如:
"GFS01_06-13-2017 05-10-18-38.csv"
"Metadata_GFS01_06-13-2017 05-10-18-38.csv"
Run Code Online (Sandbox Code Playgroud)
如何查找以...开头的列表项 "GFS01_"
在SQL中我使用查询: select item from list where item like 'GFS01_%'