查找字符串中全部的非特殊字符和对应位置的python代码
时间: 2023-03-06 12:08:02 浏览: 68
可以使用Python的内置函数re.findall()来查找字符串中的非特殊字符并获取它们的位置,代码如下:import re text = 'Hello, world!' result = re.findall(r'[^\W\d_]+', text) for i in range(len(result)):
print(result[i], i)
相关问题
查找字符串中全部的汉字和对应汉字的位置的python代码
答:可以使用Python的re模块来实现。可以使用以下代码:import restr = 'chinese string'result = re.findall(r'[\u4e00-\u9fff]+', str)for i in range(len(result)):print("汉字: %s 位置: %d" % (result[i], str.find(result[i])))
python 字符串中查找对应内容
在 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`。