Python | Append suffix/prefix to strings in list

Python | Append suffix/prefix to strings in list

In this tutorial, we will learn how to append a suffix or a prefix to strings in a list.

Problem:

Given a list of strings and a suffix or prefix, append the suffix or prefix to each string in the list.

Solution:

Appending Suffix:

To append a suffix to each string in a list, you can use list comprehension.

def append_suffix(strings, suffix): return [s + suffix for s in strings] my_strings = ["apple", "banana", "cherry"] result = append_suffix(my_strings, "_fruit") print(result) # Output: ["apple_fruit", "banana_fruit", "cherry_fruit"] 

Appending Prefix:

Similarly, to append a prefix to each string in a list, list comprehension can be used.

def append_prefix(strings, prefix): return [prefix + s for s in strings] my_strings = ["apple", "banana", "cherry"] result = append_prefix(my_strings, "fresh_") print(result) # Output: ["fresh_apple", "fresh_banana", "fresh_cherry"] 

Using map() function:

You can also achieve the same results using the map() function.

For Suffix:

def add_suffix(s): return s + "_fruit" my_strings = ["apple", "banana", "cherry"] result = list(map(add_suffix, my_strings)) print(result) # Output: ["apple_fruit", "banana_fruit", "cherry_fruit"] 

For Prefix:

def add_prefix(s): return "fresh_" + s my_strings = ["apple", "banana", "cherry"] result = list(map(add_prefix, my_strings)) print(result) # Output: ["fresh_apple", "fresh_banana", "fresh_cherry"] 

Notes:

  • List comprehension is a more concise way to transform lists in Python. It is also typically more readable than using the map() function for simple transformations.
  • Using map() can be beneficial when you already have a function defined that you want to apply to each element of a list.

This tutorial provided methods to append a suffix or a prefix to strings in a list in Python. Depending on your specific use case and personal preferences, you can choose the method that best fits your needs.


More Tags

simplejson dry matlab-table rename favicon moped sql-function batch-file puppeteer imagemagick-convert

More Programming Guides

Other Guides

More Programming Examples