search

Home  >  Q&A  >  body text

python - 单词之间只保留一个空格,用replace为什么会出错

在python中,字符串是没有contains函数的,不过可以使用find来代替。现在有一串单词,有的相邻两个单词之间可能不止一个空格,现在我只想保留一个空格,使用下面的办法就是无效的,不知道为什么这样会出现死循环。我知道可以使用' '.join(a.split())来解决问题,但是下面的代码不知道为什么会出错,是我的思想错误,还是其他原因?在java等其他语言里面,使用这种思想可行么?
def StringUnderLine(str):

str.strip();
n=0;
while str.find('  '):
    str.replace('  ',' ')
    n=n+1
    print(n,end='')
print(str,end='')

a="1 2 3 4 5 "
b="1 "
c=" 2"
d="abc def"
StringUnderLine(a)
StringUnderLine(b)
StringUnderLine(c)
StringUnderLine(d)

PHPzPHPz2911 days ago627

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:10:36

    str.find(' ') returns -1 if not found and the while loop is True to loop infinitely, so while -1 will loop infinitely
    Also, to make str.replace(' ', ' ') effective,
    should

    a = '1    3   5'
    while a.find('  ') != -1:
        a = a.replace('  ', ' ')
       
    如果只是a.replace('  ', ' '),那么循环执行的永远只是a = '1    3   5', 也就是初始字符串,
    

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 10:10:36

    str = str.replace(' ',' ');
    In JAVA, C#, the string variable itself is immutable. In other words, replace does not change the original string.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:10:36

    Let me digress first, you brother, if you ask python, you only label python, why do you label so many languages ​​​​?


    If you are not sure about the length of the space, you can use regular matching. I don’t know python, so I will give you an idea.

    I checked it out and found that all non-zero numbers in python represent true. If str.find cannot find a match, it will return -1. , if found, it will return the first matching position, so the brother above is right, if you use it as a condition, it will be equivalent to true when it is not found, but it will be regarded as false when it finds the match at position 0, so I want to see If str.find finds a match, check it out! = -1 is correct

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:10:36

    str has not been changed by assignment. replace returns a new string instead of modifying str directly

    reply
    0
  • Cancelreply