python 去除字符串中的空格

def InsStrip():
print 'please input a string'
str = raw_input('> ') # @ReservedAssignment
for i in range(len(str)):
if str[i] == ' ':
str = str[:(i-1)] + str[i:]

print str

InsStrip()

求教
错误 string index out of range
不可以使用 strip()

三种方法如下:

    用replace函数:

    your_str.replace(' ', '')
    a = 'hello word'  # 把a字符串里的word替换为python
    a.replace('word','python')  # 输出的结果是hello python

    用split断开再合上:

    ''.join(your_str.split())

    用正则表达式来完成替换:

    import re strinfo = re.compile('word')
    b = strinfo.sub('python',a) 
    print b 
    # 结果:hello python

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-07-22

将字符串中的空格去除,字符串的长度就减少了,开始计算出的len(str)长度是原始字符串的长度,下标当然会越界

print 'please input a string:'
string=raw_input('> ')
string=string.replace(' ','')
print string

本回答被网友采纳
第2个回答  推荐于2017-11-27
def InsStrip():
    print 'please input a string'
    str = raw_input('> ')  # @ReservedAssignment
    for i in range(len(str)):
        if str[i] == ' ':
            str = str[:(i-1)] + str[i:]  # i == 0 时 str[:(i-1)]越界
            
# ==> 

def insstrip(astr):
    for pre in xrange(len(astr)):
        if astr[pre] != ' ':
            break
    astr = astr[pre:]
    pos = 1
    while pos < len(astr):
        if astr[pos] != ' ':
            pos += 1
        else:
            astr = astr[:pos] + astr[pos+1:]
    return astr


insstrip("  asdf 34  afsd asdfasd   fasd  ")

本回答被提问者采纳
第3个回答  2023-09-15
1、使用strip()方法
它是一个Python内置函数,可以用来去除字符串开头和结尾的空格。例如,以下代码将使用strip()方法去除字符串开头和结尾的空格:
'''Python
string = "hello,world!"
print(string.strip())
'''
这段代码将输出字符串'hello,world!',因为他去除了开头和结尾的空格。这个方法非常简单,可以在需要去除空格字符串上直接调用。但是需要注意的是,它只会去除字符串开头和结尾的空格,而不是字符串内部的空格。
2、使用replace()方法
它可以用来替换字符串中的一些字符。我们可以使用它来替换空格字符。例如,以下代码将使用replace()方法将空格字符替换为空字符串:
'''
python
string ="hello,world!"
print(string.replace("",""))
'''
这段代码将输出字符串'hello,world!',因为它去除了字符串中的所有空格。这种方法非常有用,因为它可以去除字符串内部的所有空格,但是需要注意的是,在我们使用它之前,我们需要确定我们确实要替换所有空格字符,因为这可能会破坏字符串的格式。
3、使用正则表达式
正则表达式是一种强大的字符串处理技术,能够匹配和处理复杂的字符串。在Python中,我们可以使用re模块来使用正则表达式。例如,以下代码将使用正则表达式从字符串中去除所有空格字符:
'''python
improt re
string = "hello,world!"
pattern = re.compile(r'\s+')
print(pattern.sub(",string))
'''
这段代码将输出字符串'hello,world!',因为它去除了字符串中的所有空格。这种方法非常灵活,可以处理各种不同类型的空格字符,并且可以轻松地根据需要定制正则表达式。
相似回答