简体   繁体   中英

How to split string based on regex in Python

I'm trying to split these lines:

Germany/France/Italy

Apple/Orange/Melon

Beef/Pork

iPhone/Android

Into:

['Germany/France/Italy']

['Apple', 'Orange', 'Melon']

['Beef/Pork']

['iPhone', 'Android']

I know I have to use split with regex, but I don't know how to use that properly. I really appreciate it if you tell me to make it.

The best way to do it would be using string method split() which takes as a parameter sep which is a character based on which the string will be splited. And returns a list of splitted elements. When used with no sep argument the string would be converted to list. But more elegant use would be to use list() method instead this method converts string to list object.

countries = Germany/France/Italy
fruits = Apple/Orange/Melon
meet = Beef/Pork
phones = iPhone/Android

print(list(countries))
print(fruits.split(sep='/')
print(list(meet))
print(phones.split(sep='/')

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