【问题标题】:How i can remove a whitespace in Python?如何在 Python 中删除空格?
【发布时间】:2018-02-21 17:32:06
【问题描述】:

将 cookie 值检索到我使用的表单中:

if "HTTP_COOKIE" in os.environ:
    cookies = os.environ['HTTP_COOKIE']
    cookies = cookies.split(';')
    print cookies
    for cookie in cookies:
        cookie = cookie.split('=')
        (key,value) = cookie
        if key == "UserID":
            user_id = value
        if key == "Password":
            password = value

打印值:

print "User ID  = %s" % user_id 
print "Pasword = %s" % password

问题,只得到:

User ID = XYZ

检查我明白了:

错误在 cookie 字符串中,因为在第一个条件下它得到 true 值,但其余的只得到 false

我在代码上打印不同的部分,并得到UserID 之后的每个列表都有一个空格:

['UserID=XYZ', ' Password=XYZ123', ' Expires=Tuesday, 31-Dec-2007 23:12:40 GMT', ' Domain=www.tutorialspoint.com', ' Path=/perl', ' PHPSESSID=vgpp18anpc6vb4epi3udkumufp']

如何去除 cookie 以获取没有空格的键值对?

代码如下:

#!C:/Python27/python.exe
import os

print "Set-Cookie:UserID=XYZ"
print "Set-Cookie:Password=XYZ123"
print "Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT"
print "Set-Cookie:Domain=www.tutorialspoint.com"
print "Set-Cookie:Path=/perl"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Radio - Fourth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Example </h2>"
print "</body>"
print "</html>"


if "HTTP_COOKIE" in os.environ:
    cookies = os.environ['HTTP_COOKIE']
    cookies = cookies.split(';')
    for cookie in cookies:
        cookie = cookie.split('=')
        (key,value) = cookie
        if key == "UserID":
            user_id = value
        if key == "Password":
            password = value
else:
    print "HTTP_COOKIE not set!"

print "User ID  = %s" % user_id
print "Pasword = %s" % password

【问题讨论】:

  • 试试cookie = cookie.strip().split('=')
  • @LeoTao 不工作

标签: python python-2.7 cookies


【解决方案1】:

错误在于条带功能。

strip():
  • 仅删除文档开头和结尾的空格。
  • 仅适用于字符串,不适用于列表

这发生了:

if "HTTP_COOKIE" in os.environ:
    cookies = os.environ['HTTP_COOKIE'] 
    # cookies is now a string
    cookies = cookies.split(';')
    # cookies is now a list

解决方案是将strip() afecter cookies放在首位,但该功能不会删除所有空格。

因为我可以使用replace(" ","")

if "HTTP_COOKIE" in os.environ:
        cookies = os.environ['HTTP_COOKIE'] 
        # cookies is now a string without spaces
        cookies = cookies.replace(" ","")
        # cookies is now a list
        cookies = cookies.split(";")

结果:

用户 ID = XYZ 密码 = XYZ123

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 2013-10-10
    • 2021-07-29
    • 2011-05-15
    相关资源
    最近更新 更多