第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!',因为它去除了字符串中的所有空格。这种方法非常灵活,可以处理各种不同类型的空格字符,并且可以轻松地根据需要定制正则表达式。