Skip to main content
 首页 » 编程设计

Python 字符串连接之意外行为

2025年05月04日53dflying

我遇到了绝对最古怪 Python 行为,但我终其一生都弄不明白。运气好的话,这里有人知道发生了什么。

我正在循环以下方法:

def request_hiscores_for(name): 
  print '+++++ request_hiscores_for() running +++++'+name 
  print type(name) 
  print '  Requesting hiscores for $name using request_hiscores_for()'.replace('$name',name) 
  print '  Requesting hiscores for '+name+' using request_hiscores_for()' 
  print '  Requesting hiscores for $name using request_hiscores_for()'.replace('$name','BLA') 
  print '----- request_hiscores_for() ending ------\n' 

并且我得到以下几行的输出:

+++++ request_hiscores_for() running +++++10032 
<type 'str'> 
 using request_hiscores_for()32 
 using request_hiscores_for()32 
  Requesting hiscores for BLA using request_hiscores_for() 
----- request_hiscores_for() ending ------ 
 
+++++ request_hiscores_for() running +++++123 Lvs 2 Go 
<type 'str'> 
 using request_hiscores_for() Lvs 2 Go 
 using request_hiscores_for() Lvs 2 Go 
  Requesting hiscores for BLA using request_hiscores_for() 
----- request_hiscores_for() ending ------ 

我想指出字符串连接是如何从字面上让部分字符串消失,并以某种方式以不同的顺序连接参数。所以...帮助将不胜感激。

请您参考如下方法:

您的 name 变量的内部表示很可能类似于 -

'10032\r' 

显示上述表示的示例(特别是末尾有 \r,没有 \n 会导致问题)-

In [17]: name = '10032\r' 
 
In [19]: print('  Requesting hiscores for $name using request_hiscores_for()'.replace('$name',name)) 
 using request_hiscores_for()32 
 
In [20]: name = '123 Lvs 2 Go\r' 
 
In [21]: print('  Requesting hiscores for $name using request_hiscores_for()'.replace('$name',name)) 
 using request_hiscores_for() Lvs 2 Go 

\r 是 carriage return , 它将光标带回行首,因此之后打印的任何新字符都从行首开始打印,因此会覆盖之前打印的内容。

最有可能的是,无论您从哪里读取名称,您要么直接获取上述字符串,要么获取类似 -

name = '10032\r\n' 

但你要么单独拆分或剥离 \n,例如 -

In [22]: name = '10032\r\n123 Lvs 2 Go\r\n' 
 
In [23]: name.split('\n') 
Out[23]: ['10032\r', '123 Lvs 2 Go\r', ''] 

如果您基于 \n 进行拆分,则不要这样做,而是使用 - .splitlines() 。示例 -

In [24]: name.splitlines() 
Out[24]: ['10032', '123 Lvs 2 Go'] 

如果你正在做类似 .strip('\n') 的事情,那么不要那样做,单独使用 .strip() 来删除所有空格或.strip('\r\n')


此外,最好使用字符串格式,而不是您的替换方法。像-

print '  Requesting hiscores for {name} using request_hiscores_for()'.format(name=name)