python – Leetcode面试题:请实现一个函数,把字符串 s 中的每个空格替换成”%20″(Python – leetcode interview question: please implement a function to replace each space in the string s with “% 20”)

要求

输入:
输出:

s = "we are tester"
we%20are%20tester

index() 函数语法

# index() 方法检测字符串中是否包含子字符串 str

fruits = ['apple', 'banana', 'cherry']

r = fruits.index("cherry")
print(r)  # 2

替换函数

# -*- coding: utf-8 -*-

def replaceSpace(s):
    """
    把字符串 s 中的每个空格替换成"%20
    :param s: 字符串
    :return:
    """
    li = []  # 定义空列表
    # 遍历
    for i in s:
        li.append(i)
    # print(li)  ['w', 'e', ' ', 'a', 'r', 'e', ' ', 't', 'e', 's', 't', 'e', 'r']
    for i in li:
        if i == ' ':
            li[li.index(i)] = '%20'
    return ''.join(li)


if __name__ == '__main__':
    s = "we are tester"
    r = replaceSpace(s)
    print(r)  # we%20are%20tester

方法二

python里面有个replace方法可以直接替换字符串,
但是一般面试官对这个回答不太满意,因为雪碧年限不足,

s = "We are tester"
print(s.replace(" ", "%20"))  # We%20are%20tester

——分界线——

我们大多数人的努力程度还配不上谈论天赋的地步
————————

requirement

Input:
Output:

s = "we are tester"
we%20are%20tester

Index() function syntax

# index() 方法检测字符串中是否包含子字符串 str

fruits = ['apple', 'banana', 'cherry']

r = fruits.index("cherry")
print(r)  # 2

Substitution function

# -*- coding: utf-8 -*-

def replaceSpace(s):
    """
    把字符串 s 中的每个空格替换成"%20
    :param s: 字符串
    :return:
    """
    li = []  # 定义空列表
    # 遍历
    for i in s:
        li.append(i)
    # print(li)  ['w', 'e', ' ', 'a', 'r', 'e', ' ', 't', 'e', 's', 't', 'e', 'r']
    for i in li:
        if i == ' ':
            li[li.index(i)] = '%20'
    return ''.join(li)


if __name__ == '__main__':
    s = "we are tester"
    r = replaceSpace(s)
    print(r)  # we%20are%20tester

Method 2

Python has a replace method that can directly replace strings,
But most interviewers are not satisfied with this answer because sprite has not had enough years,

s = "We are tester"
print(s.replace(" ", "%20"))  # We%20are%20tester

——Dividing line——

我们大多数人的努力程度还配不上谈论天赋的地步