在Python中,可以使用字符串的replace()方法来替换空格。以下是一个示例代码:
def replace_spaces(string):
return string.replace(" ", "%20") # 将空格替换为"%20"
# 示例
string = "遍历字符串并替换空格的操作不如预期"
new_string = replace_spaces(string)
print(new_string)
输出:
遍历字符串并替换空格的操作不如预期
在这个示例中,replace_spaces()函数接受一个字符串作为参数,然后使用replace()方法将字符串中的空格替换为"%20"。最后,返回替换后的新字符串。
下一篇:遍历字符串的每个字母