将字符串转换为元组而不拆分字符

将字符串转换为元组而不拆分字符

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

问题描述

我正在努力将字符串转换为元组,而不在此过程中拆分字符串的字符.有人可以建议一种简单的方法来做到这一点.需要一个衬板.

I am striving to convert a string to a tuple without splitting the characters of the string in the process. Can somebody suggest an easy method to do this. Need a one liner.

失败

   a = 'Quattro TT'
   print tuple(a)

工程

  a = ['Quattro TT']
  print tuple(a)

由于我的输入是字符串,因此我尝试通过将字符串转换为列表来尝试下面的代码,该列表再次将字符串拆分为字符..

Since my input is a string, I tried the code below by converting the string to a list, which again splits the string into characters ..

失败

a = 'Quattro TT'
print tuple(list(a))

预期输出:

('Quattro TT')

生成的输出:

('Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T')

推荐答案

您可以执行(a,).无需使用功能. (请注意,逗号是必需的.)

You can just do (a,). No need to use a function. (Note that the comma is necessary.)

从本质上讲,tuple(a)意味着要构成a内容的元组,而不是仅由a本身组成的元组.字符串的内容"(迭代时得到的内容)是其字符,这就是为什么将其拆分为字符的原因.

Essentially, tuple(a) means to make a tuple of the contents of a, not a tuple consisting of just a itself. The "contents" of a string (what you get when you iterate over it) are its characters, which is why it is split into characters.

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

09-03 01:40