劍指offer python 第2題 替換空格

2022-04-28 21:42:15 字數 887 閱讀 5497

請實現乙個函式,將乙個字串中的每個空格替換成「%20」。

很容易想到用python裡的字串處理方法,比如replace和re.sub等

首先用sub,

#

-*- coding:utf-8 -*-

import

reclass

solution:

#s 源字串

defreplacespace(self, s):

return re.sub('

\s','

%20',s)

然後用replace

#

-*- coding:utf-8 -*-

import

reclass

solution:

#s 源字串

defreplacespace(self, s):

return s.replace('

','%20

')

還有一種方法就是依次取遍歷字串裡的每個字元,一旦發現有空格,就把'%20'新增到乙個空字串裡,如果沒有空格,就把原字元新增到字串裡

#

-*- coding:utf-8 -*-

import

reclass

solution:

#s 源字串

defreplacespace(self, s):

s_new=""

for i in

s:

if i=="":

i="%20"

s_new+=i

else

: s_new +=i

return s_new

劍指offer(python版) 2 替換空格

牛客網 leetcode 1 暴力解題 replace直接替換 2 從前向後記錄 數目,從前向後替換 class solution s 源字串 def replacespace self,s write code here 方法一 暴力解題 replace函式替換 s s.replace 20 re...

劍指offer(Python)替換空格

這道題要求是 將乙個字串中的空格替換成 20 有多少個空格就替換成多少個 20 例如 hello world 中間有兩個空格,則需要輸出的形式是 hello 20 20world 字串首尾的空格亦算在內。class solution def replacespace self,s return 20...

劍指offer Python 替換空格

請實現乙個函式,將乙個字串中的每個空格替換成 20 python字串,有replace方法,可以實現替換,第乙個引數是要替換的內容,第二個引數是替換的新內容 能夠快速完成,果然python作為一種高階語言,不太適合做演算法 但是 replace 相當於 insert 在替換 時,會將原字串元素的位置...