到目前为止,这是我的代码:
input1 = input("Please enter a string: ")
newstring = input1.replace(' ','_')
print(newstring)
所以如果我输入我的输入:
I want only one underscore.
目前显示为:
I_want_only_____one______underscore.
但是我希望它能像这样出现:
I_want_only_one_underscore.
答案 0 :(得分:25)
此模式将使用单个下划线替换任何空白组
newstring = '_'.join(input1.split())
如果你只想更换空格(不是tab / newline / linefeed等),那么使用正则表达式可能更容易
import re
newstring = re.sub(' +', '_', input1)
答案 1 :(得分:6)
肮脏的方式:
newstring = '_'.join(input1.split())
更好的方式(更可配置):
import re
newstring = re.sub('\s+', '_', input1)
使用replace
功能的超级超级方式:
def replace_and_shrink(t):
'''For when you absolutely, positively hate the normal ways to do this.'''
t = t.replace(' ', '_')
if '__' not in t:
return t
t = t.replace('__', '_')
return replace_and_shrink(t)
答案 2 :(得分:4)
第一种方法(不起作用)
>>> a = '213 45435 fdgdu'
>>> a
'213 45435 fdgdu '
>>> b = ' '.join( a.split() )
>>> b
'213 45435 fdgdu'
正如你所看到的,变量a在"有用的"之间包含了很多空格。子串。不带参数的split()函数和join()函数的组合可清除多个空格中的初始字符串。
如果初始字符串包含特殊字符,例如' \ n'
,则上一种技术会失败>>> a = '213\n 45435\n fdgdu\n '
>>> b = ' '.join( a.split() )
>>> b
'213 45435 fdgdu' (the new line characters have been lost :( )
为了纠正这个问题,我们可以使用以下(更复杂的)解决方案。
第二种方法(有效)
>>> a = '213\n 45435\n fdgdu\n '
>>> tmp = a.split( ' ' )
>>> tmp
['213\n', '', '', '', '', '', '', '', '', '45435\n', '', '', '', '', '', '', '', '', '', '', '', '', 'fdgdu\n', '']
>>> while '' in tmp: tmp.remove( '' )
...
>>> tmp
['213\n', '45435\n', 'fdgdu\n']
>>> b = ' '.join( tmp )
>>> b
'213\n 45435\n fdgdu\n'
第三种方法(有效)
这种方法在我眼中更加炽热。检查一下:
>>> a = '213\n 45435\n fdgdu\n '
>>> b = ' '.join( filter( len, a.split( ' ' ) ) )
>>> b
'213\n 45435\n fdgdu\n'