对 Python 来说是全新的。我正在尝试在 python 中创建一个函数,用破折号替换空格。
下面是我的代码:
def ReplaceSpace(s):
"""
Returns: returns s but with spaces replaced by dash (-) characters.
THIS CODE REPLACES EMPTY SPACES WITH DASHES
ReplaceSpace('Life is good!') returns 'Life-is-good!'
Parameter s: the input string
Precondition: s is a string
"""
spaced_string = ' '
for letter in s:
if letter == ' ':
Spaced_string = spaced_string +'_'
else:
Spaced_string = spaced_string + letter
return Spaced_string
我的代码返回: ' !而不是“生活就是美好!”
我该如何解决这个问题?
答案 0 :(得分:3)
您的代码中有几个错误,主要与缩进有关:
您的 else
应该与您的 if
对齐,而不是与您的 for
对齐。
您的 return
应该与您的功能保持一致。
由于 Python 区分大小写,因此您的代码中有两个变量:spaced_string
和 Spaced_string
。您应该只使用一个。
您的函数将空格替换为 _
而不是 -
。
def replace(s):
spaced_string = ' '
for letter in s:
if letter == ' ':
spaced_string = spaced_string + '-'
else:
spaced_string = spaced_string + letter
return spaced_string
无论哪种方式,都有更好的方法:
def replace(s):
return s.replace(' ', '-')
答案 1 :(得分:1)
Python 让你很容易。您可以对字符串使用 replace
方法。
例如:
s = 'Life is good!'
s2 = s.replace(' ', '-') # using the replace method here to replace all spaces found in s with hyphens
print("Original String : ", s)
print("Modified String : ", s2)
# s2 -> Life-is-good!
答案 2 :(得分:0)
一种更好的方法是使用正则表达式,re.sub
函数搜索模式并将其替换为提供的字符串
re.sub(r'pattern','-',string)
\s+ captures all the space in between the string
import re
def replace_space(string):
return re.sub(r'\s+','-',string)
print(replace_space('Life is good!'))
替换函数用'-'替换所有空格,例如
print('Life is good!'.replace(' ','-')) Life--is-good!