如何在Python中将电子邮件地址/密码字符串拆分为两个?

时间:2022-11-22 21:38:50

Lets say we have this string: [18] email@email.com:pwd:

假设我们有这个字符串:[18] email@email.com:pwd:

email@email.com is the email and pwd is the password.

email@email.com是电子邮件,pwd是密码。

Also, lets say we have this variable with a value

另外,假设我们将这个变量赋值

f = "[18] email@email.com:pwd:"

I would like to know if there is a way to make two other variables named var1 and var2, where the var1 variable will take the exact email info from variable f and var2 the exact password info from var2.

我想知道是否有办法制作另外两个名为var1和var2的变量,其中var1变量将从变量f获取完全的电子邮件信息,var2从var2获取确切的密码信息。

The result after running the app should be like:

运行应用程序后的结果应该是:

var1 = "email@email.com"

and

var2 = "pwd"

4 个解决方案

#1


>>> var1, var2, _ = "[18] email@email.com:pwd:"[5:].split(":")
>>> var1, var2
('email@email.com', 'pwd')

Or if the "[18]" is not a fixed prefix:

或者如果“[18]”不是固定前缀:

>>> var1, var2, _ = "[18] email@email.com:pwd:".split("] ")[1].split(":")
>>> var1, var2
('email@email.com', 'pwd')

#2


import re
var1, var2 = re.findall(r'\s(.*?):(.*):', f)[0]

If findall()[0] feels like two steps forward and one back:

如果findall()[0]感觉前进两步,后退一步:

var1, var2 = re.search(r'\s(.*?):(.*):', f).groups()

#3


var1, var2 = re.split(r'[ :]', f)[1:3]

#4


To split on the first colon ":", you can do:

要拆分第一个冒号“:”,您可以执行以下操作:

# keep all after last space
f1= f.rpartition(" ")[2]
var1, _, var2= f1.partition(":")

#1


>>> var1, var2, _ = "[18] email@email.com:pwd:"[5:].split(":")
>>> var1, var2
('email@email.com', 'pwd')

Or if the "[18]" is not a fixed prefix:

或者如果“[18]”不是固定前缀:

>>> var1, var2, _ = "[18] email@email.com:pwd:".split("] ")[1].split(":")
>>> var1, var2
('email@email.com', 'pwd')

#2


import re
var1, var2 = re.findall(r'\s(.*?):(.*):', f)[0]

If findall()[0] feels like two steps forward and one back:

如果findall()[0]感觉前进两步,后退一步:

var1, var2 = re.search(r'\s(.*?):(.*):', f).groups()

#3


var1, var2 = re.split(r'[ :]', f)[1:3]

#4


To split on the first colon ":", you can do:

要拆分第一个冒号“:”,您可以执行以下操作:

# keep all after last space
f1= f.rpartition(" ")[2]
var1, _, var2= f1.partition(":")