How to manipulate strings in Python?

Published on Aug. 22, 2023, 12:17 p.m.

String manipulation is a common task in Python programming. Here are some of the most common tasks:

  1. Concatenating strings: To concatenate two or more strings in Python, you can use the + operator or the join() method. For example:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2    # using + operator
result = " ".join([str1, str2])    # using join() method
  1. Splitting strings: To split a string into substrings based on a delimiter, you can use the split() method. For example:
str = "apple,banana,orange"
result = str.split(",")    # returns ['apple', 'banana', 'orange']
  1. Replacing substrings: To replace all occurrences of a substring within a string, you can use the replace() method. For example:
str = "Hello, World!"
result = str.replace(",", "")    # returns "Hello World!"
  1. Checking if a substring is in a string: To check if a substring is present within a string, you can use the in keyword. For example:
str = "Hello, World!"
result = "Hello" in str    # returns True
  1. Converting string case: To convert a string to upper or lower case, you can use the upper() or lower() methods. For example:
str = "Hello, World!"
result = str.upper()    # returns "HELLO, WORLD!"
result = str.lower()    # returns "hello, world!"

These are just a few examples of common string manipulation tasks in Python. Python provides many more string manipulations methods and functions, so it’s a good idea to familiarize yourself with the Python string manipulation functions.

Tags:

related content