用下划线替换字符串中的所有空格

时间:2018-10-19 06:02:29

标签: python

如何在不使用replace函数的情况下用下划线替换字符串中的空格。有人告诉我也要使用带有某种循环类型的累积字符串

string = input("Enter a string")
i = 0
acc = ""

for char in string:
    if char == " ":
        acc = string + "_"

print(acc)

4 个答案:

答案 0 :(得分:0)

尝试一下

string = input("Enter a string")
i = 0
acc = ""
newlist = [] #create a new list which will be the output
strlist = list(string) #create a list of each character in the input string
for char in strlist:
    if char == " ":
        newlist.append('_')
    newlist.append(char)    
acc = ''.join(newlist)
print(acc)

答案 1 :(得分:0)

您的代码应为:

string = input("Enter a string")
i = 0
acc = ""

for char in string:
    if char == " ":
        acc += "_"
    else:
        acc += char

print(acc)

如果没有replace,请尝试。

string = input("Enter a string")
res = ''.join(["_" if i == " " else i for i in string])
print(res)

另一种方法:

string = input("Enter a string")
res = "_".join(string.split(" "))
print(res)

答案 2 :(得分:0)

如果允许您使用split,那么

s = 'Your string with spaces'

s_ = '' 
for word in s.split():
    s_ += '_' + word

s_[1:]  # 'Your_string_with_spaces'

否则,将单词替换为'_'而不是'':

s_ = '' 
for char in s:
    if char == ' ':
        s_ += '_'
    else:
        s_ += char

答案 3 :(得分:0)

您的代码距离不太远。您可以使用这样的累积字符串:

string = input("Enter a string")
acc = ""
for char in string:
    if char == " ":
        char = "_"
    acc += char

print(acc)