py的两个字符串中数字的加减
时间: 2024-04-15 19:27:04 浏览: 20
您可以使用正则表达式来提取字符串中的数字,并进行加减运算。以下是一个示例代码:
```python
import re
def add_subtract_numbers(str1, str2):
# 从第一个字符串中提取数字
numbers1 = re.findall(r'\d+', str1)
# 从第二个字符串中提取数字
numbers2 = re.findall(r'\d+', str2)
if len(numbers1) == 0 or len(numbers2) == 0:
return "无法提取到数字,请检查输入的字符串。"
# 将提取到的数字转换为整数
number1 = int(numbers1[0])
number2 = int(numbers2[0])
# 进行加减运算
result = number1 + number2
return result
# 示例用法
string1 = "abc123"
string2 = "def456"
result = add_subtract_numbers(string1, string2)
print(result)
```
请注意,这只是一个简单示例,假设字符串中只包含一个数字。如果您的需求更复杂,请在提取数字和进行运算的部分进行适当的修改。
相关问题
py 字符串后加字符串
你可以使用加号符号 `+` 来连接两个字符串。例如:
```python
str1 = "Hello, "
str2 = "World!"
result = str1 + str2
print(result) # 输出:Hello, World!
```
另外,你也可以使用字符串的 `join()` 方法来连接多个字符串。例如:
```python
str_list = ["Hello", "World", "!"]
result = " ".join(str_list)
print(result) # 输出:Hello World !
```
在上面的例子中,`join()` 方法将 `str_list` 列表中的三个字符串用空格连接起来,并返回一个新的字符串。
py统计字符串中词语位置和个数
可以使用Python中的Counter和nltk库来实现:
```python
from collections import Counter
import nltk
text = "Hello world, hello python, hello NLTK"
tokens = nltk.word_tokenize(text)
counter = Counter(tokens)
for word, count in counter.items():
print(f"Word: {word}, Count: {count}")
```
输出结果:
```
Word: Hello, Count: 3
Word: world, Count: 1
Word: ,, Count: 2
Word: python, Count: 1
Word: NLTK, Count: 1
```
如果需要统计每个词语出现的位置,可以使用enumerate函数:
```python
for i, word in enumerate(tokens):
print(f"Word: {word}, Index: {i}")
```
输出结果:
```
Word: Hello, Index: 0
Word: world, Index: 1
Word: ,, Index: 2
Word: hello, Index: 3
Word: python, Index: 5
Word: ,, Index: 6
Word: hello, Index: 7
Word: NLTK, Index: 9
```