简体   繁体   English

Python:用另一个单词替换字符串中的某些单词? 没有内置功能?

[英]Python: Replace certain words in string with another word? Without built in functions?

Anyone know how to do this? 有人知道怎么做吗?

Ex: 例如:

Replace sstring with sreplace in string s 用s中的sreplace替换sstring

s = "111sstring111" s =“ 111sstring111”

expected output: "111sreplace111" 预期输出:“ 111sreplace111”

replacement.join(s.split(target))

i guess ... but its probably not going to help the interviewr with your grasp of algorithms ... it would only reveal your grasp of python 我猜...但是它可能不会帮助面试官掌握算法...它只会揭示您对python的掌握

re.sub(target,replacement,s) #would also work 

if you are looking for an algorithm that uses no builtins you should probably say that in the question 如果您正在寻找不使用内建函数的算法,则可能应该在问题中这样说

Here's another option, but again it mostly just tests your python knowledge. 这是另一种选择,但同样,它大多只是测试您的python知识。

index = theString.find(sstring)
if index != -1:
    theString = theString[:index] + sreplace + theString[index + len(sstring):]

Same idea, generalized for more than one occurrence: 相同的想法,适用于多次出现:

newString = ""
index = theString.find(search)
while index != -1:
    newString = newString + theString[:index] + rep 
    theString = theString[index + len(sstring):]
    index = theString.find(search)
newString += theString

Here's another option using re.sub , which is basically a more flexible str.replace : 这是另一个使用re.sub的选项,它基本上是更灵活的str.replace

>>> import re
>>> s = "111sstring111"
>>> re.sub('sstring', 'sreplace', s)
'111sreplace111'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不使用内置替换功能的情况下用另一个单词替换字符串中的单词? - How to replace a word in a string by another word without using built-in replace function? 将单词列表中的所有单词替换为python中的另一个单词 - Replace all words from word list with another string in python 用另一个词替换一个词的每个实例,而不破坏包含该词的其他词 - Replace every instance of a word with another word without breaking other words containing that word 如果它在单词列表中,则替换字符串中的单词 - Replace a word in a string if it is in a list of words 通过不使用“字符串替换功能”的索引来替换字符串中的单词-python - Replace a word in a String by indexing without “string replace function” -python 替换字符串中某些未知的单词 - replace certain not known words in a string 如果该单词在另一个单词的特定数量的单词内,则替换该单词的一个单词 - Replace one word of a string if that word is within a specific number of words of another word Python Regex - 用另一个词替换特定的词(没有哈希) - Python Regex - Replace specific word (without hash) with another word python:替换字符串中的单词 - python : replace words in string 在不使用内置 python 函数的情况下替换字符串中的短语? - Replacing phrases in string without using built-in python functions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM