Create string list python

Lists of strings in Python

This post describes how to work with lists of strings in Python. Lists are one of the most common data structures in Python, and they are often used to hold strings.

Quick examples

First we’ll give some quick examples:

# define a list of strings >>> names = ["Eve", "Alice", "Bob"] # print the list of strings >>> print(names) ['Eve', 'Alice', 'Bob'] # loop over the names list, and # print each string one at a time >>> for name in names: >>> print(name) Eve Alice Bob # add a name to the list >>> names.append("Charlie") # check if the list contains a string >>> if "Bob" in names: >>> print("Bob is here") Bob is here # add another string list to it >>> more_names = ["Ivan", "Gerth"] >>> names = names + more_names # sort the list >>> names.sort() # join the strings in the list by a comma >>> comma_separated = ", ".join(names) >>> print(comma_separated) Alice, Bob, Charlie, Eve, Gerth, Ivan 

The next sections describe these operations on string lists in more detail.

Читайте также:  background

Create list of strings

To create a list of strings, first use square brackets [ and ] to create a list. Then place the list items inside the brackets separated by commas. Remember that strings must be surrounded by quotes. Also remember to use = to store the list in a variable.

So we get something like this:

It is also allowed to put each string on a separate line:

animals = [ "deer", "beaver", "cow" ] 

Add strings to list

When you already have a list of strings and you want to add another string to it, you can use the append method:

colors = ["red", "blue", "green"] colors.append("purple") 

You can also create a new list with only one string in it and add it to the current list:

To print a whole list of strings in one line, you can simply call the built-in print function, giving the list as an argument:

colors = ["red", "blue", "green"] print(colors) 

If you want to convert a list to a string, you can use the built-in function repr to make a string representation of the list:

products = ["shelf", "drawer"] products_as_string = repr(products) print(products_as_string) 

Concatenate lists of strings

You can use the + operator to concatenate two lists of strings. For example:

colors1 = ["red", "blue"] colors2 = ["purple", "silver"] concatenated = colors1 + colors2 

Check if string is in list

You can use the in keyword to check if a list contains a string. This gives you a boolean value: either True or False . You can store this value somewhere, or use it directly in an if statement:

colors = ["pink", "cyan"] if "pink" in colors: print("yes!") has_cyan = "cyan" in colors print(has_cyan) 

Sort list of strings

To sort a list of strings, you can use the sort method:

numbers = ["one", "two", "three", "four"] numbers.sort() 

You can also use the sorted() built-in function:

numbers = ["one", "two", "three", "four"] numbers = sorted(numbers) 

Join list of strings

To join a list of strings by another string, you need to call the join method on the string, giving your list as an argument. For example, if we have this list:

And similarly, print(«|».join(colors)) will output:

Conclusion

Being able to manipulate lists of strings is crucial for Python programmers. We’ve described ways to create, modify, print, sort, and join lists of strings in Python.

Improve your Python skills fast

The fastest way to learn programming is with lots of practice. Learn a programming concept, then write code to test your understanding and make it stick. Try our online interactive Python course today—it’s free!

Want to get better at Python quickly? Try our interactive lessons today! Memberships are 100% FREE this week only!

Источник

Working with Lists of Strings in Python

To create a list of strings in Python, add comma-separated strings in between square brackets.

For example, here is a list of strings that represent names:

Now that you have a list of strings, there are lots of things you might want to do with it.

In the following, you are going to learn 10+ most common examples of what you commonly want to do with a list of strings.

List of Strings in Python

A list is a commonly used type in Python. It is used to store multiple elements in one place for easy access, update, and modification.

It is common to deal with a list of strings in Python. That’s why you are going to learn some useful things you can do with it.

Let’s start by creating a list of strings. Syntactically, there are two ways to do this.

To create a list of strings in Python, add comma-separated strings inside of square brackets. Remember to add double quotation marks around each string.

You can also declare the list of strings using multiple lines.

names = [ "Alice", "Bob", "Charlie" ]

Sometimes the expression is more readable this way. For example, when you create a long list of strings, it may be wise to spread the expression across multiple lines.

Next, let’s see some useful things you might want to do with a list of strings.

How to Print a List of Strings in Python

If you want to print the list of strings as-is, just pass it into the print() function.

names = ["Alice", "Bob", "Charlie"] print(names)

If you want to print the strings one by one, use a for-loop.

names = ["Alice", "Bob", "Charlie"] for name in names: print(name)

How to Change the Case of List of Strings

1. Lowercase

To convert a string to lowercase in Python, use the built-in lower() method of a string.

To convert a list of strings to lowercase, use a loop.

names = ["Alice", "Bob", "Charlie"] names_lower = [] for name in names: names_lower.append(name.lower()) print(names_lower)

Alternatively, you can also use a list comprehension. This is essentially a one-liner for-loop.

names = ["Alice", "Bob", "Charlie"] names_lower = [name.lower() for name in names] print(names_lower)

2. Uppercase

To turn a string to uppercase in Python, use the built-in upper() method of a string.

To turn a list of strings to uppercase, loop through the list and convert each string to upper case.

names = ["alice", "bob", "charlie"] names_upper = [name.upper() for name in names] print(names_upper)

3. Capitalize the First Letters

To capitalize the first letter of a string, call the capitalize() method.

To capitalize a whole list of strings, use a list comprehension (or for-loop) and capitalize the strings one by one.

names = ["alice", "bob", "charlie"] names_cap = [name.capitalize() for name in names] print(names_cap)

How to Sort a List of Strings in Python

Sorting data is an important ability. In Python, sorting is easy with the built-in sorted() function. Let’s see a couple of useful examples.

1. Alphabetic Sort

A very basic way to sort text data is by sorting it in alphabetical order.

In Python, calling sorted() function on a list of strings creates an alphabetical ordering of the list.

names = ["Charlie", "Alice", "Bob"] sorted_names = sorted(names) print(sorted_names)

2. Reversed Alphabetic Sort

Sometimes you want to reverse the alphabetical ordering. To do this, you can set reverse parameter True in the sorted() function.

names = ["Charlie", "Alice", "Bob"] sorted_names = sorted(names, reverse=True) print(sorted_names)

3. Sort by Length

To sort a list of strings by length (shortest first), specify the key parameter inside the sorted() function call.

names = ["Charlie", "Alice", "Bob"] sorted_names = sorted(names, key=len) print(sorted_names)

If you want to sort a list of strings in a reversed length order (longest first), you can do:

names = ["Charlie", "Alice", "Bob"] sorted_names = sorted(names, key=len, reverse=True) print(sorted_names)

How to Merge a List of Strings

To combine a list of strings, use the join() method of a string.

For example, to join a list of words to form a sentence, you can call:

words = ["This", "is", "a", "test"] sentence = " ".join(words) print(sentence)

Here the first string is » » . It acts as the separator between the combined strings.

The separator can really be anything.

For example, if you want to combine the strings by a new line, you can do:

words = ["This", "is", "a", "test"] sentence = "\n".join(words) print(sentence)

How to Filter a List of Strings in Python

To filter a list based on a criterion, you can use the built-in filter() function.

For example, let’s filter a list of names that contain the letter ‘o’ :

names = ["Charlie", "Alice", "Bob", "David"] names_with_o = list(filter(lambda name: 'o' in name, names)) print(names_with_o)

In case you are unfamiliar with lambda expressions, check out this guide for more details.

How to Convert a List of Strings into a List of Integers

Sometimes you may get data as a list of numbers. But the numbers are strings. In this case, you want to convert them to integers.

To convert a list of strings to a list of integers, use a for loop or a list comprehension.

num_strings = ["1", "2", "3", "4"] numbers = [int(number) for number in num_strings] print(numbers)

Thanks for reading. I hope you find it useful. Happy coding!

Further Reading

Источник

Python – List of Strings

In Python, List of Strings is a list which contains strings as its elements.

In this tutorial, we will learn how to create a list of strings, access the strings in list using index, modify the strings in list by assigning new values, and traverse the strings in list in a loop using while, for.

Create List of Strings

To create a list of strings, assign the comma separated string values enclosed in square brackets.

Python Program

list_of_strings = ['apple', 'banana', 'mango'] print(list_of_strings)

We can also use list() constructor to create a list of strings as shown below.

Python Program

list_of_strings = list(['apple', 'banana', 'mango']) print(list_of_strings)

Access Strings in List of Strings

To access items in list of strings, we can use index. Index starts from 0, and increments by one for subsequent elements.

Python Program

list_of_strings = ['apple', 'banana', 'mango'] print(list_of_strings[0]) print(list_of_strings[1]) print(list_of_strings[2])

Modify Strings in List of Strings

To modify items in list of strings, we can use index similar to as how we accessed strings in the above example. We have to use assignment operator and assign a new value to the element in list referenced by index.

Python Program

list_of_strings = ['apple', 'banana', 'mango'] list_of_strings[1] = "orange" print(list_of_strings)

Traverse Strings in List of Strings

Strings in List of Strings are ordered collection of items. So, we can use any looping statement: while, for loop.

In the following example, we will use for loop to traverse each string in list of strings.

Python Program

list_of_strings = ['apple', 'banana', 'mango'] for string in list_of_strings: print(string)

In the following example, we will use while loop to traverse each string in list of strings.

Python Program

list_of_strings = ['apple', 'banana', 'mango'] i = 0 while i < len(list_of_strings): print(list_of_strings[i]) i += 1

Summary

In this tutorial of Python Examples, we learned how to create, access, modify and iterate for a list of strings.

Источник

List of Strings in Python

Lists are one of the most used data structures in Python. In this article, we will discuss how to perform different operations on a list of strings in Python.

Create a List of Strings in Python

To create a list of strings, you can use the square brackets along with the string values as follows.

Here, we have created a list of strings where each string is the name of a programming language.

If you have a container object like a set or tuple of strings, you can create the list of strings using the list() constructor. The list() constructor takes a container object as its input argument and returns a list of the elements present in the container object. From a set or tuple of strings, you can create a list of strings in python using the list() constructor as follows.

In the above example, we have created a list of strings using a set of strings and the list() constructor. The order of strings in the list is not the same in the list and set because a set is an unordered container object. Hence, the order in a set doesn’t matter. Due to this, the elements of the set aren’t added to the list in a specific order. Due to this, the order of elements in the list and the set are different.

Add String to a List of Strings in Python

To add a string to a list of strings, you can use the append() method. The append() method, when invoked on a list, accepts the string as the input argument and appends the input string at the end of the list of strings as shown below.

Источник

Оцените статью