Python中的字符串连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4535944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String Concatenation in Python
提问by jkeys
Yeah, I know this little problem is pretty lame, but I'm trying out Python and I figured it'd be pretty simple. I'm having a hard time figuring out how the native data types interact in Python. Here, I am trying to concatenate different parts of the lyricsinto one long string which will be returned as output.
是的,我知道这个小问题很蹩脚,但我正在尝试 Python 并且我认为它非常简单。我很难弄清楚原生数据类型在 Python 中是如何交互的。在这里,我试图将歌词的不同部分连接成一个长字符串,该字符串将作为输出返回。
The error I receive upon trying run the script is "TypeError: cannot concatenate 'str' and 'tuple' objects." I put everything that wasn't a string in the function str(), but apparently something is still a "tuple" (a data type I've never used before).
我在尝试运行脚本时收到的错误是“TypeError:无法连接 'str' 和 'tuple' 对象。” 我把所有不是字符串的东西都放在函数 str() 中,但显然有些东西仍然是一个“元组”(一种我以前从未使用过的数据类型)。
Could someone tell me how to get whatever tuple is in there to a string so this will all concatenate smoothly?
有人能告诉我如何将其中的任何元组放入字符串中,以便所有这些都能顺利连接吗?
(P.S. I used the variable "Copy" because I wasn't sure if, when I decremented the other variable, it would mess with the for loop construct. Would it?)
(PS 我使用了变量“Copy”,因为我不确定,当我减少另一个变量时,它是否会干扰 for 循环结构。会吗?)
#99 bottles of beer on the wall lyrics
def BottlesOfBeerLyrics(NumOfBottlesOfBeer = 99):
BottlesOfBeer = NumOfBottlesOfBeer
Copy = BottlesOfBeer
Lyrics = ''
for i in range(Copy):
Lyrics += BottlesOfBeer, " bottles of beer on the wall, ", str(BottlesOfBeer), " bottles of beer. \n", \
"Take one down and pass it around, ", str(BottlesOfBeer - 1), " bottles of beer on the wall. \n"
if (BottlesOfBeer > 1):
Lyrics += "\n"
BottlesOfBeer -= 1
return Lyrics
print BottlesOfBeerLyrics(99)
Some people suggested building a list and the joining it. I edited it a little bit to what I think is what you guys meant, but could you tell me if this is the preferred method?
有些人建议建立一个列表并加入它。我对它进行了一些编辑,我认为这是你们的意思,但是你能告诉我这是否是首选方法吗?
#99 bottles of beer on the wall lyrics - list method
def BottlesOfBeerLyrics(NumOfBottlesOfBeer = 99):
BottlesOfBeer = NumOfBottlesOfBeer
Copy = BottlesOfBeer
Lyrics = []
for i in range(Copy):
Lyrics += str(BottlesOfBeer) + " bottles of beer on the wall, " + str(BottlesOfBeer) + " bottles of beer. \n" + \
"Take one down and pass it around, " + str(BottlesOfBeer - 1) + " bottles of beer on the wall. \n"
if (BottlesOfBeer > 1):
Lyrics += "\n"
BottlesOfBeer -= 1
return "".join(Lyrics)
print BottlesOfBeerLyrics(99)
采纳答案by Adam Vandenberg
The comma-separated list to the left of Lyrics +=is defining a "tuple".
左侧的逗号分隔列表Lyrics +=定义了一个“元组”。
You'll want to change the "," to "+", since string concatenation does not take a comma-separated list of values.
您需要将“,”更改为“+”,因为字符串连接不采用逗号分隔的值列表。
Also, consider building up a list of strings to concatenate then using the "join" method.
另外,考虑建立一个字符串列表来连接,然后使用“join”方法。
回答by moinudin
Lyrics += BottlesOfBeer, " bottles of beer on the wall, ", str(BottlesOfBeer), " bottles of beer. \n", \
"Take one down and pass it around, ", str(BottlesOfBeer - 1), " bottles of beer on the wall. \n"
The problem is everything after the +=is a tuple. Change all the commas to pluses and cast the first BottlesOfBeerto string.
问题+=是 a之后的一切tuple。将所有逗号更改为加号并将第一个转换BottlesOfBeer为字符串。
Lyrics += str(BottlesOfBeer) + " bottles of beer on the wall, " + str(BottlesOfBeer) + " bottles of beer. \n" + \
"Take one down and pass it around, " + str(BottlesOfBeer - 1) + " bottles of beer on the wall. \n"
Short demonstration:
简短演示:
>>> a = 'hello', 'world'
>>> b = 'hello' + 'world'
>>> type(a)
<type 'tuple'>
>>> type(b)
<type 'str'>
A better way to format the string would be to use string formatters:
格式化字符串的更好方法是使用字符串格式化程序:
Lyrics += '%(orig)d bottles of beer on the wall, %(orig)d bottles of beer.\n' \
'Take one down and pass it around, %(now)d bottles of beer on the wall.\n' % \
{ 'orig': BottlesOfBeer, 'now': BottlesOfBeer-1 }
Your variable names should start with a lower case letter, else they are easily confused with class names. Ideally though, you should follow pep 8and use lowercase with words separated by underscores.
变量名应该以小写字母开头,否则很容易与类名混淆。理想情况下,您应该遵循pep 8并使用小写字母和下划线分隔的单词。
You do not need the Copyvariable, as a copy of BottlesOfBeerwill be passed to range(). Same story with BottlesOfBeer = NumOfBottlesOfBeer, you can use and modify NumOfBottlesOfBeerthroughout the function.
您不需要该Copy变量,因为 的副本BottlesOfBeer将传递给range(). 与 相同BottlesOfBeer = NumOfBottlesOfBeer,您可以NumOfBottlesOfBeer在整个函数中使用和修改。
Since you have a default argument NumOfBottlesOfBeer = 99, you don't need to pass 99when calling BottlesOfBeerLyrics.
由于您有一个默认参数NumOfBottlesOfBeer = 99,因此99在调用BottlesOfBeerLyrics.
回答by Mark Byers
Don't use string concatenation for this. Put the strings in a list and join the list at the end. I'd also suggest using str.format.
不要为此使用字符串连接。将字符串放入列表中并在最后加入列表。我还建议使用str.format.
verse = "{0} bottles of beer on the wall, {0} bottles of beer.\n" \
"Take one down and pass it around, {1} bottles of beer on the wall.\n"
def bottles_of_beer_lyrics(bottles=99):
lyrics = []
for x in range(bottles, 0, -1):
lyrics.append(verse.format(x, x-1))
return '\n'.join(lyrics)
You could also get the result more directly by using a generator expression:
您还可以使用生成器表达式更直接地获得结果:
def bottles_of_beer_lyrics(bottles=99):
return '\n'.join(verse.format(x, x-1) for x in range(bottles, 0, -1))
As a final point you should note that "1 bottles" is not grammatically correct. You may want to create a function that can give you the correct form of "bottle" depending on the number. If internationalization is an issue (I know it's probably not) then you should also be aware that some languageshave more forms than just "singular" and "plural".
最后一点,您应该注意“1 瓶”在语法上是不正确的。您可能想要创建一个函数,该函数可以根据数字为您提供正确形式的“瓶子”。如果国际化是一个问题(我知道可能不是),那么您还应该意识到某些语言的形式不仅仅是“单数”和“复数”。
回答by Keith
The comma operator creates a tuple. The line "Lyrics += ..." is creating a tuple on the right side.
逗号运算符创建一个元组。“Lyrics += ...”这一行在右侧创建了一个元组。
To concatenate strings in Python use the "+" operator.
要在 Python 中连接字符串,请使用“+”运算符。
Lyrics += str(BottlesOfBeer) + " bottles of beer..." + ...
However, that's still not the preferred way for this kind of thing, but is fine for learning string concatenation.
然而,这仍然不是这种事情的首选方式,但对于学习字符串连接来说很好。
回答by martineau
Looks like you've got the original problem cleared up and are now asking about using join()-- yes, that's generally a better than using +=for string concatenation (although not always faster).
看起来您已经解决了原始问题,现在正在询问使用join()- 是的,这通常比+=用于字符串连接更好(尽管并不总是更快)。
But even better is to not even do it or do so as little as possible. Python had something called format strings which are something like those used by C's printf()function -- see Format String Syntaxin the online documentation. Using that along with the format()string method (and some other Pythonisms) can really simplify things:
但更好的是甚至不做或尽可能少做。Python 有一种叫做格式字符串的东西,它类似于 Cprintf()函数使用的格式字符串——请参阅在线文档中的格式字符串语法。将它与format()string 方法(以及其他一些 Python 主义)一起使用可以真正简化事情:
def BottlesOfBeerLyrics(NumOfBottlesOfBeer=99):
PluralSuffix = lambda n: "s" if n != 1 else ""
Stanza = "\n".join([
"{0} bottle{1} of beer on the wall, {0} bottle{1} of beer.",
"Take one down and pass it around, {2} bottle{3} of beer on the wall.",
"\n"])
Lyrics = ""
for Bottles in range(NumOfBottlesOfBeer, 0, -1):
Lyrics += Stanza.format(Bottles, PluralSuffix(Bottles),
Bottles-1, PluralSuffix(Bottles-1))
return Lyrics
print BottlesOfBeerLyrics(3)
# 3 bottles of beer on the wall, 3 bottles of beer.
# Take one down and pass it around, 2 bottles of beer on the wall.
#
# 2 bottles of beer on the wall, 2 bottles of beer.
# Take one down and pass it around, 1 bottle of beer on the wall.
#
# 1 bottle of beer on the wall, 1 bottle of beer.
# Take one down and pass it around, 0 bottles of beer on the wall.

