正在尝试使用.替换为Python编辑字符串

正在尝试使用.替换为Python编辑字符串,python,replace,Python,Replace,我有一个字符串: some_string = "I rode my bike 100' North toward the train station" 我想将('North)部分改为('N),以便该部分显示为(…我的自行车100'N朝向…)等 现在写我正在努力: some_string = some_string.replace("' North ", "' N ") 但它只是保持不变 我不想使用任何像.replace('orth','')这样的技巧,因为我希望它能处理较长的句子,可能包括'

我有一个字符串:

some_string = "I rode my bike 100' North toward the train station"
我想将('North)部分改为('N),以便该部分显示为(…我的自行车100'N朝向…)等

现在写我正在努力:

some_string = some_string.replace("' North ", "' N ")
但它只是保持不变

我不想使用任何像.replace('orth','')这样的技巧,因为我希望它能处理较长的句子,可能包括'North'的实例,但附近没有撇号

为什么我的第一种方法不起作用

请帮忙

编辑:

所以我通过在另一个字符串中搜索得到第一个字符串

由于某种原因,Python返回它,因此撇号是另一种撇号!!?将其与未转义的单引号区分开来

some_string = '’'
^看起来是这样的(复制并粘贴了它)。那是从哪里来的?我怎么用键盘把它打出来?Wtf

编辑2:


我从Adobe PDF获取第一个字符串。我认为它的格式是一个“花哨的引号”,你可以通过按住Alt键并在数字键盘上键入0146来获得它

字符串是不可变的,这意味着它们不能更改;同样,此方法返回一个新字符串,但不会就地编辑。您只需将已有的代码分配给一个变量。您甚至可以将上述代码的输出分配给同一个变量,这样变量名现在就指向不同的字符串(即您想要的字符串)。

如果您分配一个新变量,这将起作用

some_string = "I rode my bike 100' North toward the train station"
new_string = some_string.replace("North ", " N ")
print(new_string)
>> I rode my bike 100'  N toward the train station
试一试

相反

请注意,有一个文档,告诉您

str.replace(旧的、新的[计数])
返回一个字符串的副本,其中所有出现的子字符串old都替换为new。如果给定了可选参数计数,则仅替换第一次出现的计数


我在编辑时调用bs,它工作正常,请参见

结果:

在Python中(通常在大多数高级编程语言中),
string
是不可变的。你不能改变它。实际上,您可以生成另一个字符串

因此,为了实现您的目标,我提出以下建议:

some_string = "I rode my bike 100' North toward the train station"
some_string = some_string.replace("' North ", "' N ") # assign the new string to the old string
print(some_string)
输出:
“我骑自行车以100'N的速度向火车站驶去”


是否将替换赋值给新变量?字符串
.replace()
方法返回一个新字符串;它不会修改现有字符串。你的代码对我来说很好。你从哪里得到这个奇怪的撇号?您是从Word还是其他文字处理器复制/粘贴的?看起来你得到了一个“聪明的报价”。好的。那么,你实现了你的目标吗?
some_string = "I rode my bike 100' North toward the train station"
some_string = some_string.replace("' North ", "' N ")
print(some_string)
I rode my bike 100' N toward the train station
some_string = "I rode my bike 100' North toward the train station"
some_string = some_string.replace("' North ", "' N ") # assign the new string to the old string
print(some_string)