python - 将转义字符 (\n) 添加到字符串元组中的最后一个元素

标签 python

我有一个像这样的字符串元组:

stringTuple = ['String1', 'String2', 'String3', 'String4', 'String5', 'String6']

我后来将此元组与多个其他元组结合起来并输入到 Excel 文档中。我需要在每个元组之间换行 - 所以我需要它看起来像这样。

stringTuple = ['String1', 'String2', 'String3', 'String4', 'String5', 'String6\n']

我研究了不同类型的字符串连接,例如: stringTuple[-1:] = stringTuple[-1:] + '\n' 运气不好

最佳答案

列表中的最后一个元素是stringTuple[-1]

向列表中的最后一个元素添加换行符:

stringTuple[-1] = stringTuple[-1] + "\n"

或者只是:

stringTuple[-1] += "\n"

顺便说一句,stringTuple[-1:]是数组的一部分(有趣的阅读是在另一个SO问题中, Understanding slice notation )。 stringTuple[start:] 生成列表中从索引 start 开始的所有项目的列表。在本例中,stringTuple[-1:] 是从最后一个索引开始的所有项目的列表(即原始列表中最后一个项目的列表):

stringTuple = ['String1', 'String2', 'String3', 'String4', 'String5', 'String6']

print(stringTuple[-1:]) # ['String6']

使用元组进行此操作

元组是不可变的,所以你不能就地修改(如果你想修改元组中的项目,你实际上需要创建一个新的元组,其中包含修改后的项目):

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')

请注意特殊符号(lastItemWithLineBreak,),它用于创建由单个元素lastItemWithLineBreak组成的元组。

关于python - 将转义字符 (\n) 添加到字符串元组中的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59768848/

相关文章:

python - 找到具有最低分数的所需项目的集合

python - py2exe 可执行文件以看似随机的方式崩溃

python - lxml - 当文件名的值相同时,从循环/迭代 Excel 行中保存 xml 会导致错误

python - 如何修复 libpapi.so.* 在运行带跟踪的 (py)COMPSs 时无法打开共享对象文件?

python - Tp-Link M7350 4G LTE 路由器 - 使用带有 Raspberry Pi 的 python 脚本发送短信

python - 如何解释 `scipy.stats.kstest` 和 `ks_2samp` 以评估 `fit` 的数据分布?

python - 对 NumPy 数组进行索引,忽略索引数组中的 NaN

python - 任意颜色条

python - 对所选列进行分组和标准化 Pandas DF

Python,如何从另一个类中调用实例方法