python给定一个字符串"123456789"写出显示所有奇数的表达式
时间: 2023-11-25 13:06:18 浏览: 31
以下是 Python 代码,可以显示所有奇数:
```python
s = "123456789"
odd = [int(i) for i in s if int(i) % 2 != 0]
print(odd)
```
输出结果为:
```
[1, 3, 5, 7, 9]
```
希望能帮到您!如果您有其他问题,请继续提问。
相关问题
python正则表达式匹配一个字符串
可以使用Python内置的re模块进行正则表达式匹配。下面是一个简单的例子,匹配一个字符串中的所有数字:
```python
import re
string = "Hello 123 World 456"
pattern = r"\d+"
matches = re.findall(pattern, string)
print(matches)
```
输出结果为:
```
['123', '456']
```
在上面的例子中,我们使用了`\d+`的正则表达式模式来匹配字符串中的所有数字。`+`符号表示匹配一个或多个数字。`re.findall()`函数返回一个包含所有匹配项的列表。
用Python写一个匹配所有字符串位置的脚本
### 回答1:
以下是一个简单的 Python 脚本,可以匹配所有字符串位置:
```python
import re
def find_all_positions(text, pattern):
positions = []
for match in re.finditer(pattern, text):
positions.append(match.start())
return positions
text = "Hello world, hello python, hello machine learning"
pattern = "hello"
positions = find_all_positions(text, pattern)
print(positions)
```
输出:
```
[0, 13, 26]
```
解释:
该脚本使用了 Python 内置的 `re` 模块,其中 `re.finditer()` 方法返回一个迭代器,可以遍历所有匹配的结果。每个结果都是一个 `MatchObject` 对象,其中包含匹配的起始位置。在循环中,将每个匹配的起始位置添加到一个列表中,并最终返回该列表。在上述示例中,我们查找字符串中所有出现 "hello" 的位置,找到了三个位置,分别是 0、13 和 26。
### 回答2:
在Python中,你可以使用re模块(正则表达式)来编写一个匹配所有字符串位置的脚本。下面是一个示例代码:
```python
import re
# 定义要匹配的字符串
text = "Python is a powerful programming language. Python is also easy to learn."
# 定义要匹配的模式
pattern = "Python"
# 使用re.finditer()函数查找所有匹配的位置
matches = re.finditer(pattern, text)
# 遍历匹配结果
for match in matches:
# 获取匹配的位置
start = match.start()
end = match.end()
# 打印匹配位置
print(f"Found match at position {start} to {end-1}")
```
这个例子中,我们首先导入了re模块,然后定义了要匹配的字符串和模式。通过使用re.finditer()函数,我们可以找到所有匹配模式的位置,返回一个迭代器对象。然后,我们可以使用for循环遍历迭代器中的每个匹配对象,并使用.start()和.end()方法获取匹配的起始位置和结束位置。最后,我们打印出每个匹配的位置。
对于给定的例子,脚本将会打印出:
```
Found match at position 0 to 5
Found match at position 34 to 39
```
这表示在字符串中找到了两个匹配模式"Python"的位置,第一个匹配起始于索引0,结束于索引5,第二个匹配起始于索引34,结束于索引39。
### 回答3:
可以使用Python中的re模块来编写一个匹配所有字符串位置的脚本。下面是一个示例:
```python
import re
def find_all_matches(pattern, text):
matches = re.finditer(pattern, text)
positions = [match.span() for match in matches]
return positions
text = "Hello, my name is John. John is a programmer."
pattern = r"John"
result = find_all_matches(pattern, text)
print(result)
```
在这个示例中,我们定义了一个`find_all_matches`函数,它接受一个正则表达式模式和一个字符串作为参数。函数使用`re.finditer`函数来查找所有与模式匹配的部分。然后,我们使用`match.span()`方法获取每个匹配的位置范围,并将其存储在一个列表中。最后,我们将列表打印出来。
在上述代码中,我们的模式是"John",而待匹配的文本是包含两个"John"字符串的句子。运行这段代码会输出`[(20, 24), (27, 31)]`,这表示第一个"John"的位置范围是从索引20到索引24,第二个"John"的位置范围是从索引27到索引31。
你可以根据需要自定义模式和文本来匹配所有字符串位置。注意,在使用正则表达式进行匹配时,需要注意模式的写法以及特殊字符的转义。