make an input string into a list in python

  • Last Update :
  • Techknowledgy :

The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string. If a delimiter is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.,In this program, we will try to convert a given string to a list, where spaces or any other special characters, according to the users choice, are encountered. To do this we use the split() method in string.,Method#3 : Using re.findall() method This task can be performed using regular expression. We can used the pattern to matched all the alphabet and make list with all the matched elements. ,WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri

1._
string.split("delimiter")
2._
Input: "Geeks for Geeks"
Output: ['Geeks', 'for', 'Geeks']

Input: "Geeks-for-Geeks"
Output: ['Geeks', 'for', 'Geeks']

Output:

['Geeks', 'for', 'Geeks']

['G', 'e', 'e', 'k', 's']
1._
Input: "Geeks for Geeks"
Output: ['Geeks', 'for', 'Geeks']

Input: "Geeks-for-Geeks"
Output: ['Geeks', 'for', 'Geeks']

Output:

['Geeks', 'for', 'Geeks']

Output:

List of character is: ['A', 'B', 'C', 'D']

['G', 'e', 'e', 'k', 's']

['g', 'e', 'e', 'k', 's']

The converted list: ['geeks', 2, 'for', 4, 'geeks', 3]

Suggestion : 2

Remote Work 2022 , Remote Work 2022

Syntax:

string.split(delimiter, maxsplit)

Code to Convert string to list in Python

str_1 = "Hire the top 1% freelance developers"
list_1 = str_1.split()
print(list_1)

#Output:
   #['Hire', 'the', 'top', '1%', 'freelance', 'developers']
str_1 = "Hire-the-top-1%-freelance-developers"

list_1 = str_1.split("-")
print(list_1)

#Output:
   #['Hire', 'the', 'top', '1%', 'freelance', 'developers']

Suggestion : 3

Certainly, if the input string is something like “abcd”, typecasting the string into a list using the list() method gives us a list having the individual characters ‘a’, ‘b’, ‘c’, ‘d’ as its elements. Take a look at the given example code below.,And as we can observe, typecasting the string using the list() method gives us a list of the member characters, as required,What if we need a list of characters present in a string? In that case, direct type conversion from string to list in Python using the list() method does the job for us.,Here in this tutorial, we are going to deal with all the methods using which we can convert a string to list in Python for different cases. Below we have listed all the methods:

#given string
string1 = "Python is great"

#printing the string
print("Actual String: ", string1)

#gives us the type of string1
print("Type of string: ", type(string1))

print("String coverted to list :", string1.split())
#prints the list given by split()
#given string
string1 = "AskPython"

#printing the string
print("Actual String: ", string1)
#confirming the type()
print("Type of string: ", type(string1))

#type - casting the string into list using list()
print("String coverted to list :\n", list(string1))
#Given string
string1 = "This is Python"

print("The actual string:", string1)

#converting string1 into a list of strings
string1 = string1.split()

#applying list method to the individual elements of the list string1
list1 = list(map(list, string1))

#printing the resultant list of lists
print("Converted to list of character list :\n", list1)
#given string
string1 = "abc,def,ghi"
print("Actual CSV String: ", string1)
print("Type of string: ", type(string1))

#spliting string1 into list with ','
as the parameter
print("CSV coverted to list :", string1.split(','))
#string with integers sepated by spaces
string1 = "1 2 3 4 5 6 7 8"
print("Actual String containing integers: ", string1)
print("Type of string: ", type(string1))

#coverting the string into list of strings
list1 = list(string1.split())
print("Converted string to list : ", list1)

#typecasting the individual elements of the string list into integer using the map() method
list2 = list(map(int, list1))
print("List of integers : ", list2)

Suggestion : 4

We have made use of the input_string.split(“,”) function to split the string separated by commas and convert it into a list of string to be used in the program.,If you look closely, you will find that we have made use of the function input_string.split() to split the input string separated by spaces from the user and converted them into individual elements to be added into a list.,Similar to the earlier example, we accepted an input list from the user in the form of a string separated by commas.,We have also made use of the For loop and converted every element into an integer to calculate its sum.

Take a look at the example program below, which accepts a list of numbers as an input in Python.

input_string = input("Enter a list element separated by space ")
list = input_string.split()
print("Calculating sum of element of input list")
sum = 0
for num in list:
   sum += int(num)
print("Sum = ", sum)

Similar to the above program, we have the ability to create a program in Python to accept a list of strings from the user. Take a look at the example below to understand this better.

input_string = input("Enter family members separated by comma ")
family_list = input_string.split(",")
print("Printing all family member names")
for name in family_list:
   print(name)

Example 1

# creating an empty list
lst = []
# number of elemetns as input
n = int(input("Enter number of elements : "))
# iterating till the range
for i in range(0, n):
   ele = int(input())
lst.append(ele) # adding the element
print(lst)

Example 3

# number of elements
n = int(input("Enter number of elements : "))
# Below line read inputs from user using map()
function
a = list(map(int, input("nEnter the numbers : ").strip().split()))[: n]
print("nList is - ", a)

Example 4

lst = []
n = int(input("Enter number of elements : "))
for i in range(0, n):
   ele = [input(), int(input())]
lst.append(ele)
print(lst)

Suggestion : 5

We can convert a string to list in Python using split() function. Python String split() function syntax is:

str.split(sep = None, maxsplit = -1)

Let’s look at a simple example where we want to convert a string to list of words i.e. split it with the separator as white spaces.

s = 'Welcome To JournalDev'
print(f 'List of Words ={s.split()}')

If we want to split a string to list based on whitespaces, then we don’t need to provide any separator to the split() function. Also, any leading and trailing whitespaces are trimmed before the string is split into a list of words. So the output will remain same for string s = ' Welcome To JournalDev ' too. Let’s look at another example where we have CSV data into a string and we will convert it to the list of items.

s = 'Apple,Mango,Banana'
print(f 'List of Items in CSV ={s.split(",")}')

Output: List of Characters =['a', 'b', 'c', '$', ' ', '#', ' ', '3', '2', '1', ' '] If you don’t want the leading and trailing whitespaces to be part of the list, you can use strip() function before converting to the list.

s = ' abc '

print(f 'List of Characters ={list(s.strip())}')