我想要一种有效的方法在Python中将一个字符串附加到另一个字符串.
var1 = "foo"
var2 = "bar"
var3 = var1 + var2
Run Code Online (Sandbox Code Playgroud)
有没有什么好的内置方法可供使用?
由于Python string无法更改,我想知道如何更有效地连接字符串?
我可以这样写:
s += stringfromelsewhere
Run Code Online (Sandbox Code Playgroud)
或者像这样:
s = []
s.append(somestring)
later
s = ''.join(s)
Run Code Online (Sandbox Code Playgroud)
在写这个问题时,我发现了一篇很好的文章谈论这个话题.
http://www.skymind.com/~ocrow/python_string/
但它是在Python 2.x.中,所以问题是在Python 3中做了哪些改变?
我是Python的新手,我完全感到困惑,.join()因为我已经阅读过它是连接字符串的首选方法.
我试过了:
strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring().join(strid)
Run Code Online (Sandbox Code Playgroud)
有类似的东西:
5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5
Run Code Online (Sandbox Code Playgroud)
它为什么这样工作?不应该595只是自动附加?
当我们使用时,我们的代码需要10分钟来虹吸68,000条记录:
new_file = new_file + line + string
Run Code Online (Sandbox Code Playgroud)
但是,当我们执行以下操作时,只需1秒钟:
new_file += line + string
Run Code Online (Sandbox Code Playgroud)
这是代码:
for line in content:
import time
import cmdbre
fname = "STAGE050.csv"
regions = cmdbre.regions
start_time = time.time()
with open(fname) as f:
content = f.readlines()
new_file_content = ""
new_file = open("CMDB_STAGE060.csv", "w")
row_region = ""
i = 0
for line in content:
if (i==0):
new_file_content = line.strip() + "~region" + "\n"
else:
country = line.split("~")[13]
try:
row_region = regions[country]
except KeyError:
row_region = "Undetermined"
new_file_content += …Run Code Online (Sandbox Code Playgroud) 因此,我正在用Python 3.4编写一个文本游戏,该游戏print()经常需要使用该函数来向用户显示变量。
我一直使用的两种方法是使用字符串格式设置和字符串连接:
print('{} has {} health left.'.format(player, health))
Run Code Online (Sandbox Code Playgroud)
和,
print(player + ' has ' + str(health) + ' health left.')
Run Code Online (Sandbox Code Playgroud)
那么哪个更好呢?它们既具有可读性,又能快速键入,并且性能完全相同。哪一个是Pythonic,为什么?
问了一个问题,因为我在与Java无关的Stack Overflow上找不到答案。
我正在尝试创建一个函数f(x),它会"-"在每个字母之间添加一个:
例如:
f("James")
Run Code Online (Sandbox Code Playgroud)
应输出为:
J-a-m-e-s-
Run Code Online (Sandbox Code Playgroud)
如果您可以使用简单的python函数,我会喜欢它,因为我是编程新手.提前致谢.另外,请使用"for"功能,因为这是我正在努力学习的内容.
编辑:
是的,我确实想要"-"之后的"s".
我有以下python代码片段:
LL=[]
for i in range(3):
LL.append("a"+str(i))
print LL
Run Code Online (Sandbox Code Playgroud)
输出如下:
['a0', 'a1', 'a2']
Run Code Online (Sandbox Code Playgroud)
如何打印(使用print LL):
[a0, a1, a2]
Run Code Online (Sandbox Code Playgroud)
即没有引号?如果我使用以下代码:
print "[",
for i in range (len(LL)-1):
print LL[i] + ", ",
print LL[i+1]+"]"
Run Code Online (Sandbox Code Playgroud)
这打印 [a0, a1, a2]