python 字符串中查找对应内容
时间: 2023-12-30 18:04:39 浏览: 26
在 Python 中,你可以使用 `find` 或 `index` 方法来查找一个字符串中是否包含另一个字符串,并返回它的位置。这两个方法的区别在于,如果字符串中不包含要查找的子字符串,`find` 方法会返回 `-1`,而 `index` 方法会抛出一个 `ValueError` 异常。
例如,如果你想要在字符串 `s` 中查找子字符串 `hello`,可以使用以下代码:
```python
s = "hello world"
pos = s.find("hello")
if pos != -1:
print("Found at position", pos)
else:
print("Not found")
```
这会输出 `Found at position 0`,因为子字符串 `hello` 在字符串 `s` 的开头。如果要使用 `index` 方法,可以将 `if` 语句替换为一个 `try...except` 块:
```python
s = "hello world"
try:
pos = s.index("hello")
print("Found at position", pos)
except ValueError:
print("Not found")
```
这同样会输出 `Found at position 0`。
相关问题
python查找字符串中的词
你可以使用Python中的split()函数来查找字符串中的词。split()函数可以将字符串以空格或指定的分隔符分割成一个词列表。下面是一个示例代码:
```python
sentence = "I love programming with Python"
words = sentence.split()
for word in words:
print(word)
```
输出结果将会是:
```
I
love
programming
with
Python
```
如果你想以其他分隔符进行分割,可以在split()函数中传入对应的分隔符作为参数,例如:
```python
sentence = "I,love,programming,with,Python"
words = sentence.split(',')
for word in words:
print(word)
```
输出结果将会是:
```
I
love
programming
with
Python
```
希望可以帮助到你!如果有任何问题,请随时提问。
python在CSV文件中通过查找某字符串对应的行列
您可以使用Python中的csv模块来读取CSV文件,并使用一个循环来查找特定字符串对应的行和列。
以下是一个示例代码,假设您要查找的字符串为"example":
```python
import csv
with open('file.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
# 查找特定字符串
for row_index, row in enumerate(csv_reader):
if "example" in row:
col_index = row.index("example")
print(f"Found 'example' at row {row_index} and column {col_index}")
```
在这个示例代码中,我们首先使用`csv.reader()`函数来读取CSV文件。然后我们使用一个循环来遍历每一行,如果该行中包含特定字符串,则使用`index()`方法来查找该字符串所在的列索引。最后,我们输出该字符串所在的行和列索引。
请注意,这个示例代码假设您的CSV文件没有标题行。如果您的CSV文件包含标题行,您需要在循环之前使用`next()`函数来跳过标题行。