python搜索字符串s中是否存在字符串'the',如存在返回其位置序号
时间: 2023-05-18 12:03:17 浏览: 77
可以使用字符串的 find() 方法来搜索字符串中是否存在指定的子字符串,如果存在则返回其位置序号,否则返回 -1。具体实现代码如下:
```
s = "This is the string that we want to search."
pos = s.find('the')
if pos != -1:
print("The position of 'the' in the string is:", pos)
else:
print("The string 'the' is not found in the string.")
```
输出结果为:
```
The position of 'the' in the string is: 27
```
相关问题
搜索字符串s中是否存在字符串'the',如存在返回其位置序号
可以使用Python中的find()方法来搜索字符串s中是否存在字符串'the',如果存在则返回其位置序号,如果不存在则返回-1。代码如下:
```
s = "This is the string to search for the word 'the'."
pos = s.find('the')
if pos != -1:
print("The word 'the' is found at position", pos)
else:
print("The word 'the' is not found in the string.")
```
输出结果为:
```
The word 'the' is found at position 30
```
python将文件中的字符串前加上序号1,2,3
可以使用Python的文件操作和字符串操作来实现这个功能。以下是一种可能的实现方式:
```python
with open('input.txt', 'r') as f_in, open('output.txt', 'w') as f_out:
# 逐行读取输入文件
for i, line in enumerate(f_in, start=1):
# 在每行字符串前加上序号和空格,并写入输出文件
f_out.write(f'{i} {line}')
```
这里使用了Python的`enumerate`函数来遍历输入文件的每一行,并给每一行字符串前加上一个递增的序号。注意在写入输出文件时,要用`\n`来表示换行。