如何用0替换空字符串,但如果不为空则不管它

Joe*_*ing 5 python replace strip

在下面显示的情况下替换值时,Python的行为似乎不一致(使用python 3.6.5)

    >>> emptyString = '    '
    >>> emptyString.strip().replace('','0') #produces expected results
    '0'
    >>> notEmptyString = ' 50 '
    >>> notEmptyString.strip().replace('','0') #expected '50'
    '05000'
    >>> shortString = notEmptyString.strip()
    >>> shortString  #results as expected
    '50'
    >>> shortString.replace('','0') #unexpected results - expected '50'
    '05000'
Run Code Online (Sandbox Code Playgroud)

这是我想看到的:

  • 如果string有一个值,只需strip()前导和尾随空格.
  • 如果string为空(即"")或string只是空白字符(即""),则将其删除为""并将""替换为"0"

示例#1 ... string ="10"....然后只删除前导和尾随空格
Example#2 ... string =''....然后转换为'0'

我可以通过其他方式获得我想要的结果,但我想知道是否有人理解为什么python会产生这些结果.

K. *_*uhr 5

如果s是字符串,则:

s.replace(old, new)
Run Code Online (Sandbox Code Playgroud)

返回一个 的副本,s字符串的每次出现都old替换为new,例如:

In [7]: "abracadabra".replace("a","4")
Out[7]: '4br4c4d4br4'
Run Code Online (Sandbox Code Playgroud)

作为一种特殊情况,如果old是空字符串,它会new在字符串的开头和结尾以及每对字符之间插入:

In [8]: "12345678".replace("","_")
Out[8]: '_1_2_3_4_5_6_7_8_'
Run Code Online (Sandbox Code Playgroud)

基本原理是在第一个字符之前、每对字符之间和最后一个字符之后有一个“空字符串”,这就是被替换的内容。

所以,replace没有按照你的想法去做。

要做什么,您可以使用已经提出的解决方案之一,或者如果您觉得自己很聪明,可以使用类似的方法:

s.strip() or "0"
Run Code Online (Sandbox Code Playgroud)


Aks*_*kar 2

正如@coldspeed 在评论中建议的那样,您需要:

def myfunc(string): return string if string.strip() else '0'


print(myfunc(' 050  '))
print(myfunc('   '))
print(myfunc(''))
print(myfunc('abcd'))
Run Code Online (Sandbox Code Playgroud)

输出:

 050  
0
0
abcd
Run Code Online (Sandbox Code Playgroud)