我怎么能不数字符串之间的空格呢

2024-10-01 17:38:34 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有,p.e,这个字符串:'I love python',我想把所有的空格都转换成'.'。我的问题是,我还需要删除外部空格,这样我就不会以这样的结果结束:“\u I\u love\u python\u”,更像这样的“I\u love\u python” 我搜索并发现我可以用一行代码来开发它mystring.strip().replace(" ", "_"),不幸的是,这是我不能在我的文章中应用的最大值。 所以我得到的是:

frase= str(input('Introduza: '))

aux=''


for car in frase:
    if car==' ':
        car='_'
        aux+=car
    else:
        aux+=car



print(aux)

我现在的问题是删除那些外部空间。我所想的是在字符串的开始处运行另一个,在最后运行另一个,直到他们找到一个非空格字符为止。但不幸的是我没能做到。。。你知道吗

感谢你所能提供的一切帮助!你知道吗


Tags: 字符串代码forinput文章carreplacestrip
3条回答

可以使用以下技巧删除字符串中的前导空格和尾随空格:

s = ' I love python   '

ind1 = min(len(s) if c == ' ' else n for n, c in enumerate(s))
ind2 = max(0 if c == ' ' else n for n, c in enumerate(s))

s = ''.join('_' if c == ' ' else c for c in s[ind1:ind2 + 1])

print('*', s, '*', sep='')

输出:

*I_love_python*

我想出了以下解决办法:

您对字符串进行迭代,但不是在字符串出现时立即用下划线替换空格,而是存储遇到的空格数。然后,一旦到达非空格字符,就将找到的空格数量添加到字符串中。因此,如果字符串以大量空格结尾,它将永远不会到达非空格字符,因此永远不会添加下划线。你知道吗

为了在开头去掉空格,我添加了一个条件来添加下划线:“我以前遇到过非空格字符吗?”你知道吗

代码如下:

text = "   I love   python    e  "

out = ""

string_started = False
underscores_to_add = 0
for c in text:
    if c == " ":
        underscores_to_add += 1
    else:
        if string_started:
            out += "_" * underscores_to_add
        underscores_to_add = 0
        string_started = True
        out += c

print(out)  # prints "I_love___python____e"

如果不允许使用strip()方法

def find(text):
    for i, s in enumerate(text):
        if s !=  " ":
            break
    return i

text = "   I love   python    e  "
text[find(text):len(text)-find(text[::-1])].replace(" ","_")

texts = ["   I love   python    e  ","I love   python    e"," I love   python    e","I love   python    e ", "I love   python    e"]
for text in texts:
    print (text[find(text):len(text)-find(text[::-1])].replace(" ","_"))

输出:

I_love___python____e I_love___python____e I_love___python____e I_love___python____e I_love___python____e

  • 给定一个字符串find将找到字符串中的第一个非空格字符
  • 使用find查找第一个非空格字符和最后一个非空格字符
  • 使用上面找到的索引获取子字符串
  • 将上述子字符串中的所有空格替换为“\”

相关问题 更多 >

    热门问题