Python 3:将元组转换为字符串 [英] Python 3: Converting A Tuple To A String

查看:124
本文介绍了Python 3:将元组转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

var_one = var_two[var_three-1]var_one = "string_one" + var_1

我需要对它执行以下操作:

var_four = 'string_two', var_one

但是,这会返回以下错误:

TypeError: 无法将元组"对象隐式转换为 str

我尝试过诸如 str(var_one) 和使用 strip 之类的东西,但这些都不起作用.我该怎么做才能达到我想要的结果?

编辑 - 以下是变量包含的内容:

var_one:新变量

var_two: 元组

var_three:整数

var_four:新

编辑 2:

程序中出错的那一行是:os.system(var_four)

解决方案

你的代码看起来很好.

尝试运行 import pdb;pdb.set_trace() 在你的程序中查看是否可以找到触发错误的行.

您需要使用 ''.join(var_four)var_four 转换为字符串,然后再将其添加到任何内容是你想使用它.请注意,这实际上会创建一个新字符串,而不是覆盖 var_four.请参阅 Python 3 string.join() 等效?

此外,您应该使用 subprocess 模块而不是 os.system.请参阅 Python 3.x 文档.>

I have the following code:

var_one = var_two[var_three-1]
var_one = "string_one" + var_1

And I need to do the following to it:

var_four = 'string_two', var_one

However, this returns the following error:

TypeError: Can't convert 'tuple' object to str implicity

I have tried things such as str(var_one) and using strip but these did not work. What can I do to achieve the result I require?

EDIT - Here are what the variables contain:

var_one: new variable

var_two: tuple

var_three: integer

var_four: new

EDIT2:

The line in the program that makes the error is: os.system(var_four)

解决方案

Your code looks fine as is.

Try running import pdb; pdb.set_trace() in your program to see if you can find the line triggering the error.

EDIT: You'll want to use ''.join(var_four) to convert var_four into a string before adding it to whatever it is you want to use it. Please note that this will actually create a new string and not overwrite var_four. See Python 3 string.join() equivalent?

Also, you should be using the subprocess module instead of os.system. See the Python 3.x documentation.

这篇关于Python 3:将元组转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆