字符串转换返回null

时间:2018-04-12 09:32:40

标签: python

尝试转换此字符串(放入变量a1):

 '\'redis_import\':\'start\',\'redis_import\':\'dim_user_level\''

为:

'\'start\':\'redis_import\',\'dim_user_level\':\'redis_import\''

我已尝试print a1.split(',').reverse(),但这会返回null。为什么?以及如何在不使用循环的情况下实现这一目标?

感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

首先,Option Explicit Private Sub Workbook_Open() Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets("Tabelle4") Dim LastRow As Long 'always use long instead of integer LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row Dim iRow As Long For iRow = 2 To LastRow AddListValidation ws.Cells(iRow, "A"), ws.Cells(iRow, "B") Next iRow End Sub Sub AddListValidation(cellSource As Range, cellTarget As Range) cellTarget.Value = "Select your values here" With cellTarget.Validation .Delete .Add Type:=xlValidateList, Formula1:=cellSource.Value .IgnoreBlank = True .InCellDropdown = True .InputTitle = "" .ErrorTitle = "" .InputMessage = "" .ErrorMessage = "" .ShowInput = True .ShowError = True End With End Sub 方法反转列表并返回.reverse()

所以你可以使用reversed()来返回列表反向的迭代器

None

答案 1 :(得分:2)

如果你想把它作为一个词典。

s = '\'redis_import\':\'start\',\'redis_import\':\'dim_user_level\''
res = {}
for i in s.split(","):
    val =  list(reversed(i.split(":")))
    res[val[0].replace("'", "")] = val[1].replace("'", "")    
print(res)

<强>输出:

{'start': 'redis_import', 'dim_user_level': 'redis_import'}

答案 2 :(得分:1)

在逗号上拆分,在冒号上拆分,反转,加入冒号,加入逗号:

s = '\'redis_import\':\'start\',\'redis_import\':\'dim_user_level\''
','.join(':'.join(i.split(':')[::-1]) for i in s.split(','))
#"'start':'redis_import','dim_user_level':'redis_import'"

要更好地理解这一点,只需观察这些不同调用的输出:

>>> s.split(',')
["'redis_import':'start'", "'redis_import':'dim_user_level'"]
>>> s.split(',')[0]
"'redis_import':'start'"
>>> s.split(',')[0].split(':')
["'redis_import'", "'start'"]
>>> s.split(',')[0].split(':')[::-1]
["'start'", "'redis_import'"]
>>> ','.join(('a', 'b', 'c'))
'a,b,c'
>>> [i[::-1] for i in [[1,2], [3,4]]]
[[2, 1], [4, 3]]

进一步阅读: