Python 将字符串转换为元组而不拆分字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16449184/
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
Converting string to tuple without splitting characters
提问by Shankar
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.
我正在努力将字符串转换为元组,而不在此过程中拆分字符串的字符。有人可以建议一种简单的方法来做到这一点。需要一个衬里。
Fails
失败
a = 'Quattro TT'
print tuple(a)
Works
作品
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 ..
由于我的输入是一个字符串,我通过将字符串转换为列表来尝试下面的代码,该列表再次将字符串拆分为字符..
Fails
失败
a = 'Quattro TT'
print tuple(list(a))
Expected Output:
预期输出:
('Quattro TT')
Generated Output:
生成的输出:
('Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T')
采纳答案by BrenBarn
You can just do (a,). No need to use a function. (Note that the comma is necessary.)
你可以这样做(a,)。无需使用函数。(注意逗号是必须的。)
Essentially, tuple(a)means to make a tuple of the contentsof a, not a tuple consisting of just aitself. The "contents" of a string (what you get when you iterate over it) are its characters, which is why it is split into characters.
本质上,tuple(a)意味着创建一个包含 的内容的a元组,而不是一个仅a由其自身组成的元组。字符串的“内容”(迭代它时得到的)是它的字符,这就是它被拆分成字符的原因。
回答by moooeeeep
Have a look at the Python tutorial on tuples:
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:
>>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',)
一个特殊的问题是包含 0 或 1 个项目的元组的构造:语法有一些额外的怪癖来适应这些。空元组由一对空括号构成;包含一项的元组是通过在值后面加上逗号来构造的(将单个值括在括号中是不够的)。丑陋,但有效。例如:
>>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',)
If you put just a pair of parentheses around your string object, they will only turn that expression into an parenthesized expression(emphasis added):
如果您只在字符串对象周围放置一对括号,它们只会将该表达式转换为带括号的表达式(添加了强调):
A parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list.
An empty pair of parentheses yields an empty tuple object. Since tuples are immutable, the rules for literals apply (i.e., two occurrences of the empty tuple may or may not yield the same object).
Note that tuples are not formed by the parentheses, but rather by use of the comma operator.The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.
带括号的表达式列表产生表达式列表产生的任何结果:如果列表包含至少一个逗号,则产生一个元组;否则,它产生构成表达式列表的单个表达式。
一对空括号产生一个空元组对象。由于元组是不可变的,文字规则适用(即,空元组的两次出现可能会或可能不会产生相同的对象)。
请注意,元组不是由括号形成的,而是使用逗号运算符形成的。例外是空元组,因为它需要括号——在表达式中允许没有括号的“无”会导致歧义并允许常见的错别字未被发现。
That is (assuming Python 2.7),
即(假设 Python 2.7),
a = 'Quattro TT'
print tuple(a) # <-- you create a tuple from a sequence
# (which is a string)
print tuple([a]) # <-- you create a tuple from a sequence
# (which is a list containing a string)
print tuple(list(a)) # <-- you create a tuple from a sequence
# (which you create from a string)
print (a,) # <-- you create a tuple containing the string
print (a) # <-- it's just the string wrapped in parentheses
The output is as expected:
输出如预期:
('Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T')
('Quattro TT',)
('Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T')
('Quattro TT',)
Quattro TT
To add some notes on the print statement. When you try to create a single-element tuple as part of a printstatement in Python 2.7 (as in print (a,)) you need to use the parenthesized form, because the trailing comma of print a,would else be considered part of the print statement and thus cause the newline to be suppressed from the output and not a tuple being created:
在打印语句上添加一些注释。当您尝试在 Python 2.7 中创建单元素元组作为打印语句的一部分时(如print (a,)),您需要使用带括号的形式,因为 的尾随逗号print a,将被视为打印语句的一部分,从而导致换行从输出中被抑制,而不是被创建的元组:
A '\n' character is written at the end, unless the print statement ends with a comma.
'\n' 字符写在末尾,除非打印语句以逗号结尾。
In Python 3.x most of the above usages in the examples would actually raise SyntaxError, because in Python 3 printturns into a function(you need to add an extra pair of parentheses).
But especially this may cause confusion:
在 Python 3.x 中,示例中的大部分上述用法实际上都会引发SyntaxError,因为在 Python 3 中print变成了一个函数(您需要添加一对额外的括号)。但特别是这可能会引起混淆:
print (a,) # <-- this prints a tuple containing `a` in Python 2.x
# but only `a` in Python 3.x
回答by igorgruiz
Just in case someone comes here trying to know how to create a tuple assigning each part of the string "Quattro" and "TT" to an element of the list, it would be like this
print tuple(a.split())
以防万一有人来这里想知道如何创建一个元组,将字符串“Quattro”和“TT”的每个部分分配给列表的一个元素,它会是这样的
print tuple(a.split())
回答by mike rodent
Subclassing tuple where some of these subclass instances may need to be one-string instances throws up something interesting.
子类化元组其中一些子类实例可能需要是单字符串实例会抛出一些有趣的东西。
class Sequence( tuple ):
def __init__( self, *args ):
# initialisation...
self.instances = []
def __new__( cls, *args ):
for arg in args:
assert isinstance( arg, unicode ), '# arg %s not unicode' % ( arg, )
if len( args ) == 1:
seq = super( Sequence, cls ).__new__( cls, ( args[ 0 ], ) )
else:
seq = super( Sequence, cls ).__new__( cls, args )
print( '# END new Sequence len %d' % ( len( seq ), ))
return seq
NB as I learnt from this thread, you have to put the comma after args[ 0 ].
注意,正如我从该线程中了解到的,您必须将逗号放在args[ 0 ].
The print line shows that a single string does not get split up.
打印行显示单个字符串没有被拆分。
NB the comma in the constructor of the subclass now becomes optional :
注意子类的构造函数中的逗号现在变为可选:
Sequence( u'silly' )
or
或者
Sequence( u'silly', )
回答by Shameem
I use this function to convert string to tuple
我使用此函数将字符串转换为元组
import ast
def parse_tuple(string):
try:
s = ast.literal_eval(str(string))
if type(s) == tuple:
return s
return
except:
return
Usage
用法
parse_tuple('("A","B","C",)') # Result: ('A', 'B', 'C')
In your case, you do
在你的情况下,你做
value = parse_tuple("('%s',)" % a)
回答by Konstantin Kozlenko
This only covers a simple case:
这仅涵盖一个简单的情况:
a = ‘Quattro TT'
print tuple(a)
If you use only delimiter like ‘,', then it could work.
如果您只使用像 ',' 这样的分隔符,那么它可以工作。
I used a string from configparserlike so:
我使用了configparser这样的字符串:
list_users = (‘test1', ‘test2', ‘test3')
and the i get from file
tmp = config_ob.get(section_name, option_name)
>>>”(‘test1', ‘test2', ‘test3')”
In this case the above solution does not work. However, this does work:
在这种情况下,上述解决方案不起作用。但是,这确实有效:
def fot_tuple(self, some_str):
# (‘test1', ‘test2', ‘test3')
some_str = some_str.replace(‘(‘, ”)
# ‘test1', ‘test2', ‘test3')
some_str = some_str.replace(‘)', ”)
# ‘test1', ‘test2', ‘test3'
some_str = some_str.replace(“‘, ‘”, ‘,')
# ‘test1,test2,test3'
some_str = some_str.replace(“‘”, ‘,')
# test1,test2,test3
# and now i could convert to tuple
return tuple(item for item in some_str.split(‘,') if item.strip())
回答by sameer_nubia
You can use the following solution:
您可以使用以下解决方案:
s="Hyman"
tup=tuple(s.split(" "))
output=('Hyman')
回答by Anselmo Blanco Dominguez
See:
看:
'Quattro TT'
is a string.
是一个字符串。
Since string is a list of characters, this is the same as
由于字符串是一个字符列表,这与
['Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T']
Now...
现在...
['Quattro TT']
is a list with a string in the first position.
是一个在第一个位置带有字符串的列表。
Also...
还...
a = 'Quattro TT'
list(a)
is a string convertedinto a list.
是转换为列表的字符串。
Again, since string is a list of characters, there is not much change.
同样,由于 string 是一个字符列表,因此没有太大变化。
Another information...
另一个信息...
tuple(something)
This convert something into tuple.
这将某些内容转换为元组。
Understanding all of this, I think you can conclude that nothing fails.
了解了所有这些,我想您可以得出结论,没有任何事情会失败。

