简体   繁体   English

在字符前后获取字符串,然后将其设置为变量Python

[英]Get String Before And After Character Then Set Them As a Variable Python

If I want to get two string separated by a character then set them as a variable how would I go about doing that? 如果我想用字符分隔两个字符串,然后将它们设置为变量,我该怎么做?

An example: 一个例子:

john:doe

I want to set "john" to variable fname, and "doe" to variable lname. 我想将“ john”设置为变量fname,将“ doe”设置为变量lname。 I would want my outcome of the script to look like the following: 我希望脚本的结果如下所示:

    print  fname
    john
    print lname
    doe

All help is appreciated. 感谢所有帮助。 Thanks! 谢谢!

Split the string by : and unpack the results: :分割字符串,然后解压缩结果:

>>> s = "john:doe"
>>> s.split(':')
['john', 'doe']
>>> fname, lname = s.split(':')
>>> fname
'john'
>>> lname
'doe'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM