将字符串列表拆分为各自的字符Python

时间:2017-10-09 06:04:35

标签: python split

我们说我有一个清单:

list = ['foo', 'bar', 'bak']

我想将这些字符串拆分成字符,这样我就可以为每个字符赋值(I.E. f = 5,o = 15,等等)。

我如何分解这些列表? 我正在考虑将每个元素转换为自己的列表,并将每个元素称为该列表的一个项目,但我不确定如何去做。

6 个答案:

答案 0 :(得分:3)

字符串在Python中是可迭代的,所以你可以像这样遍历它们:

list = ['foo', 'bar', 'bak']

for item in list:
    for character in item:
        print(character)

答案 1 :(得分:0)

尝试为每个单词做范围功能

list = ['foo','bar','bak']

for i in range (len(list)):
    for t in range(len(list[i])):
        print(list[i][t])

它会打印每件物品。 如果你想创建每个字母的列表, 尝试

list = ['foo','bar','bak']
letters = []

for i in range (len(list)):
    for t in range(len(list[i])):
        letters.append(list[i][t])

答案 2 :(得分:0)

如果这就是你在这里寻找的东西:

       package hjwt

    import (
        "fmt"
        "time"

        jwt "github.com/dgrijalva/jwt-go"
        "github.com/hzwy23/hcloud/logs"
    )

    var (
        key []byte = []byte("-jwt-hzwy23@163.com")
    )

    // json web token
    func GenToken() string {
        claims := &jwt.StandardClaims{
            NotBefore: int64(time.Now().Unix()),
            ExpiresAt: int64(time.Now().Unix() + 1000),
            Issuer:    "hzwy23",
        }

        token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
        ss, err := token.SignedString(key)
        if err != nil {
            logs.Error(err)
            return ""
        }
        return ss
    }

    // Verify that token is valid
    func CheckToken(token string) bool {
        _, err := jwt.Parse(token, func(*jwt.Token) (interface{}, error) {
            return key, nil
        })
        if err != nil {
            fmt.Println("parase with claims failed.", err)
            return false
        }
        return true
    }


   // Next, add the filter before the beego starts. The filter code is as follows:

     beego.InsertFilter("/platform/*", beego.BeforeRouter, func(ctx *context.Context) {
            cookie, err := ctx.Request.Cookie("Authorization")
            if err != nil || !hjwt.CheckToken(cookie.Value) {
                http.Redirect(ctx.ResponseWriter, ctx.Request, "/", http.StatusMovedPermanently)
            }
        })

  //  In this process, you need to set the JSON web token value to cookies, where the cookies method is set as follows in.Golang:


    token := hjwt.GenToken()
    cookie := http.Cookie{Name: "Authorization", Value: token, Path: "/", MaxAge: 3600}
    http.SetCookie(w, &cookie)

答案 3 :(得分:0)

也许这就是你要转换成字符列表的内容:

l = ['foo', 'bar', 'bak']

list(''.join(l))

答案 4 :(得分:0)

您可以使用一行解决方案:

list1 = ['foo', 'bar', 'bak']
print([j for i in list1 for j in i])

结果:

['f', 'o', 'o', 'b', 'a', 'r', 'b', 'a', 'k']

答案 5 :(得分:-1)

将整个列表加入每个角色

my_list = [' foo',' bar',' bak']

result = list('' .join(my_list))

结果

[' f',' o',' o',' b',' a',& #39; r',' b',' a',' k']

现在您可以遍历结果以为每个字符分配值