[英]Add escape character (\n) to last element in tuple of strings
I have a tuple of strings like this:我有一个像这样的字符串元组:
stringTuple = ['String1', 'String2', 'String3', 'String4', 'String5', 'String6']
I later combine this tuple with multiple others and input into an excel document.后来我将这个元组与多个其他元组组合并输入到一个 excel 文档中。 I need new line break between each of these tuples - so I need it to look like this.
我需要在每个元组之间换行 - 所以我需要它看起来像这样。
stringTuple = ['String1', 'String2', 'String3', 'String4', 'String5', 'String6\\n']
I've looked into different sorts of string concatenation such as: stringTuple[-1:] = stringTuple[-1:] + '\\n'
with no luck我研究了不同类型的字符串连接,例如:
stringTuple[-1:] = stringTuple[-1:] + '\\n'
没有运气
The last element in your list is stringTuple[-1]
.列表中的最后一个元素是
stringTuple[-1]
。
Add a line break to the last element in your list:向列表中的最后一个元素添加换行符:
stringTuple[-1] = stringTuple[-1] + "\n"
Or just:要不就:
stringTuple[-1] += "\n"
By the way, stringTuple[-1:]
is a slice of your array (an interesting read is in another SO question, Understanding slice notation ).顺便说一下,
stringTuple[-1:]
是你数组的一个切片(一个有趣的读物是在另一个 SO 问题, Understanding slice notation )。 stringTuple[start:]
yields a list of all the items in a list, from index start
onwards. stringTuple[start:]
生成列表中所有项目的列表,从索引start
。 In this case, stringTuple[-1:]
is a list of all your items from the last index onwards (ie a list of the last item in your original list):在这种情况下,
stringTuple[-1:]
是从最后一个索引开始的所有项目的列表(即原始列表中最后一个项目的列表):
stringTuple = ['String1', 'String2', 'String3', 'String4', 'String5', 'String6']
print(stringTuple[-1:]) # ['String6']
Tuples are immutable, so you can't make modifications in place (if you want to modify items in a tuple, you actually need to create a new tuple with the modified items in it):元组是不可变的,所以你不能就地进行修改(如果你想修改元组中的项目,你实际上需要创建一个包含修改项目的新元组):
stringTuple = ('String1', 'String2', 'String3', 'String4', 'String5', 'String6')
# get last item in tuple, add line break to it
lastItemWithLineBreak = stringTuple[-1] + "\n"
# create a new tuple consisting of every item in our original list but the last
# and then add our new modified item to the end
newTuple = tuple(i for i in stringTuple[:-1]) + (lastItemWithLineBreak,)
print(newTuple) # ('String1', 'String2', 'String3', 'String4', 'String5', 'String6\n')
Note the special notation (lastItemWithLineBreak,)
, which is used to create a tuple consisting of the single element lastItemWithLineBreak
.请注意特殊符号
(lastItemWithLineBreak,)
,它用于创建由单个元素lastItemWithLineBreak
组成的元组。
简单的解决方案,为元组的最后一个元素添加结束行:
stringTuple[-1] += '\n'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.