python中一个字符串怎么去除空格

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python中一个字符串怎么去除空格相关的知识,希望对你有一定的参考价值。

参考技术A s = 'a b c '
s.replace(' ','') #利用'',替换掉空格' '。

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

参考技术A

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

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

参考技术B 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  ")

本回答被提问者采纳

以上是关于python中一个字符串怎么去除空格的主要内容,如果未能解决你的问题,请参考以下文章

python 去除字符串中的空格

python字符串中怎么忽略空格前面的数字

python几种去掉字符串中间空格的方法

怎么去除一个字符串的前后空格

python如何去除字符串里面的空格

python怎么取消字符串之间的空格