我的理解是Python字符串是不可变的.
我尝试了以下代码:
a = "Dog"
b = "eats"
c = "treats"
print a, b, c
# Dog eats treats
print a + " " + b + " " + c
# Dog eats treats
print a
# Dog
a = a + " " + b + " " + c
print a
# Dog eats treats
# !!!
Run Code Online (Sandbox Code Playgroud)
Python不应该阻止这项任务吗?我可能错过了一些东西.
任何的想法?
我正在研究CTCI的一个问题.
第1章的第三个问题是你带一个字符串如
'Mr John Smith '
并要求您用以下内容替换中间空格%20:
'Mr%20John%20Smith'
作者在Python中提供了这个解决方案,称之为O(n):
def urlify(string, length):
'''function replaces single spaces with %20 and removes trailing spaces'''
counter = 0
output = ''
for char in string:
counter += 1
if counter > length:
return output
elif char == ' ':
output = output + '%20'
elif char != ' ':
output = output + char
return output
Run Code Online (Sandbox Code Playgroud)
我的问题:
我理解这是从左到右扫描实际字符串的O(n).但是Python中的字符串不是不可变的吗?如果我有一个字符串,我用+操作符添加另一个字符串,它是否分配必要的空格,复制原始字符串,然后复制附加字符串?
如果我有一个n长度为1 的字符串集合,则需要:
1 + 2 + 3 + 4 …
加入清单:
>>> ''.join([ str(_) for _ in xrange(10) ])
'0123456789'
Run Code Online (Sandbox Code Playgroud)
join 必须采取迭代.
显然,join这个论点是[ str(_) for _ in xrange(10) ],这是一个列表理解.
看这个:
>>>''.join( str(_) for _ in xrange(10) )
'0123456789'
Run Code Online (Sandbox Code Playgroud)
现在,join这个论点只是str(_) for _ in xrange(10),不[],但结果是一样的.
为什么?是否str(_) for _ in xrange(10)也会产生一个列表或一个可迭代?
我正在阅读The Hitchhiker的Python指南,还有一个简短的代码片段
foo = 'foo'
bar = 'bar'
foobar = foo + bar # This is good
foo += 'ooo' # This is bad, instead you should do:
foo = ''.join([foo, 'ooo'])
Run Code Online (Sandbox Code Playgroud)
作者指出''.join()并不总是比它快+,所以他并不反对使用+字符串连接.
但为什么foo += 'ooo'不好的做法却被foobar=foo+bar认为是好的?
foo += bar好?foo = foo + 'ooo'好?在此代码片段之前,作者写道:
关于字符串的最后一件事是使用join()并不总是最好的.在您从预定数量的字符串创建新字符串的实例中,使用加法运算符实际上更快,但在上述情况下或者在您添加到现有字符串的情况下,使用join()应该是你喜欢的方法.
我在早期的帖子中询问了最有效的大规模动态字符串连接方法,我建议使用join方法,这是最好,最简单,最快速的方法(就像大家所说的那样).但是当我玩字符串连接时,我发现了一些奇怪的(?)结果.我确信事情正在发生,但我不能完全理解.这是我做的:
我定义了这些功能:
import timeit
def x():
s=[]
for i in range(100):
# Other codes here...
s.append("abcdefg"[i%7])
return ''.join(s)
def y():
s=''
for i in range(100):
# Other codes here...
s+="abcdefg"[i%7]
return s
def z():
s=''
for i in range(100):
# Other codes here...
s=s+"abcdefg"[i%7]
return s
def p():
s=[]
for i in range(100):
# Other codes here...
s+="abcdefg"[i%7]
return ''.join(s)
def q():
s=[]
for i in range(100):
# Other codes here...
s = s + ["abcdefg"[i%7]]
return ''.join(s) …Run Code Online (Sandbox Code Playgroud) 我想for line in file在python中做一个方法,其中行尾被重新定义为我想要的任何字符串.另一种说法是我想从文件而不是行读取记录; 我希望它与阅读线一样快速和方便.
这是python,相当于设置perl的$/输入记录分隔符,或者Scanner在java中使用.这不一定要使用for line in file(特别是,迭代器可能不是文件对象).只是等同于避免将太多数据读入内存的东西.
另请参阅: 添加对使用任意分隔符读取记录到标准IO堆栈的支持
python ×6
string ×4
algorithm ×1
file ×1
immutability ×1
io ×1
mutability ×1
performance ×1
record ×1
separator ×1