我有以下字符串:

text_one = str("\"A Ukrainian American woman who lives near Boston, Massachusetts, told Fox News Digital on Monday that she can no longer speak on the phone with her own mother, who lives in southern Ukraine, because of the Russian attacks on Ukraine and the fear these attacks have engendered.")

text_two = str("\n\nMany people in southern Ukraine — as well as throughout the country — are right now living in fear for their lives as Russian soldiers overtake the area, the Boston-area woman said.\"")

我需要用$替换每个s/s实例,但要替换给定单词中的first个s/s实例.因此,输入/输出如下所示:

> Mississippi
> Mis$i$$ippi

我的 idea 是,在每个字符之后,先跳过"s",然后替换所有其他字符,直到"character",但我不知道该怎么做.我还考虑创建一个列表来处理每个单词.

推荐答案

re的解决方案:

import re

text_one = '"A Ukrainian American woman who lives near Boston, Massachusetts, told Fox News Digital on Monday that she can no longer speak on the phone with her own mother, who lives in southern Ukraine, because of the Russian attacks on Ukraine and the fear these attacks have engendered.'
text_two = '\n\nMany people in southern Ukraine — as well as throughout the country — are right now living in fear for their lives as Russian soldiers overtake the area, the Boston-area woman said."'


def replace(s):
    return re.sub(
        r"(?<=[sS])(\S+)",
        lambda g: g.group(1).replace("s", "$").replace("S", "$"),
        s,
    )


print(replace(text_one))
print(replace(text_two))

打印:

"A Ukrainian American woman who lives near Boston, Mas$achu$ett$, told Fox News Digital on Monday that she can no longer speak on the phone with her own mother, who lives in southern Ukraine, because of the Rus$ian attacks on Ukraine and the fear these attacks have engendered.


Many people in southern Ukraine — as well as throughout the country — are right now living in fear for their lives as Rus$ian soldier$ overtake the area, the Boston-area woman said."

Python相关问答推荐

Class_weight参数不影响RandomForestClassifier不平衡数据集中的结果

具有多个选项的计数_匹配

对整个 pyramid 进行分组与对 pyramid 列子集进行分组

如何使用LangChain和AzureOpenAI在Python中解决AttribeHelp和BadPressMessage错误?

用合并列替换现有列并重命名

在Python中动态计算范围

如何根据一列的值有条件地 Select 前N个组,然后按两列分组?

Django RawSQL注释字段

Geopandas未返回正确的缓冲区(单位:米)

为什么常规操作不以其就地对应操作为基础?

找到相对于列表索引的当前最大值列表""

在Admin中显示从ManyToMany通过模型的筛选结果

在Docker容器(Alpine)上运行的Python应用程序中读取. accdb数据库

如果包含特定值,则筛选Groupby

pandas:在操作pandora之后将pandora列转换为int

仅取消堆叠最后三列

如何在Python中实现高效地支持字典和堆操作的缓存?

使用Scikit的ValueError-了解

Python:在cmd中添加参数时的语法

关于数字S种子序列内部工作原理的困惑