简体   繁体   中英

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. 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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