Sitemap

Python guide on using “Strings”

5 min readJul 17, 2023

--

Press enter or click to view image in full size

Strings are a fundamental data type in Python that represent sequences of characters.

Creating a String: A string can be created by enclosing characters/words in single quotes (‘’), double quotes (“”) or triple quotes (“”” “””).

#Creating a String
s1 = 'Hello World'
s2 = "Python"
"""This is a multi-line string."""

Accessing Characters: Individual characters/item in a string can be accessed using indexing. The index starts at 0 for the first character, -1 for the last character, and negative indices are counted from the end of the string. Note a black space is also considered as item and is indexed within a string.

#Accessing Characters
s1 = "Hello, World!"
print(s1[0])
# Output: 'H'
print(s1[-1])
# Output: '!'

String Length: The length of a string can be found using the len() function.

#String Length
s1 = "Hello, World!"
print(len(s1))
# Output: 13

String Concatenation: Strings can be concatenated using the + operator.

#String Concatenation
s1 = "Hello"
s2 = "World"
s1s2 = str1 + " " + str2
print(s1s2)
# Output: 'Hello World'
#notice the use of a space inbetween " ".

Slicing strings: A substring can be extracted from a string using slicing. The syntax for slicing is string[start:end:step], where start is the starting index, end is the ending index (exclusive), and step is the step size (optional).

#Slicing strings
s1 = "Hello, World!"
print(s1[7:12])
# Output: 'World'
#extracting every 2nd item from the string
print(s2[::2])
# Output: 'Hlo ol!'

String Methods: Strings have many built-in methods that allow you to manipulate and modify them. Some of these are mentioned below:-

  • upper(): Converts all characters to uppercase.
  • lower(): Converts all characters to lowercase.
  • strip(): Removes leading and trailing whitespace.
  • split(): Splits the string into a list of substrings based on a delimiter.
  • join(): Joins a list of strings into one string using a specified delimiter.
  • replace(): Replaces all occurrences of a substring with another substring.
  • find(): Searches for a substring and returns its index (or -1 if not found).
s1 = "   Hello, World!   "
print(s1.upper())
# Output: ' HELLO, WORLD! '

print(s1.strip())
# Output: 'Hello, World!'

print(s1.split(','))
# Output: [' Hello', ' World! ']

print('-'.join(['Hello', 'World']))
# Output: 'Hello-World'

print(s1.replace('Hello', 'Hi'))
# Output: ' Hi, World! '

print(s1.find('World'))
# Output: 9

String Concatenation with Other Data Types: A strings can be concatenated with other data types by converting them to strings using the str() function. This allows you to combine strings with numbers, booleans, or other data types.

age = 25 #integer type data

message = "I am " + str(age) + " years old."
#converting the integer using type casting

print(message)
# Output: I am 25 years old.

String Formatting with f-strings: Python 3.6 introduced formatted string literals, also known as f-strings. They provide a concise and convenient way to embed expressions inside string literals, allowing you to include variables and expressions directly within curly braces {}.

#f-string
name = "Anita"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message)
# Output: My name is Anita and I am 25 years old.

Using .format() allows you to dynamically insert values into the string, making it more flexible and reusable. You can provide the values directly as arguments to the .format() method

#format()

name = "Anita"
age = 25
height = 5.4

# Format the string using positional placeholders
message = "My name is {} and I am {} years old. My height is {} feet.".format(name, age, height)
print(message)
# Output: My name is Anita and I am 25 years old. My height is 5.4 feet.

# Format the string using named placeholders
message = "My name is {n} and I am {a} years old. My height is {h} meters.".format(n=name, a=age, h=height)
print(message)
# Output: My name is Anita and I am 25 years old. My height is 5.4 feet.

# Format the string using indexed placeholders
message = "My name is {0} and I am {1} years old. My height is {2} meters.".format(name, age, height)
print(message)
# Output: My name is Anita and I am 25 years old. My height is 5.4 feet.

Raw Strings: Python provides raw strings, indicated by the r or R prefix, which treat backslashes \ as literal characters. Raw strings are often used when working with regular expressions or file paths.

path = r"C:\Users\ABC\Documents\file1.txt"
print(path)
# Output: C:\Users\ABC\Documents\file1.txt

String Membership: You can check if a substring exists within a string using the in and not in operators. These operators return a boolean value indicating whether the substring is present or not.

#String membership
s = "Python is a powerful language."

print("powerful" in s)
# Output: True

print("Java" not in s)
# Output: True

String Encoding and Decoding: Python supports various string encoding schemes, such as UTF-8, ASCII, and more. You can encode a string to bytes using the encode() method and decode bytes to a string using the decode() method.

#Encoding Decoding

s = "Hello, World!"

encoded_bytes = s.encode("utf-8")

decoded_string = encoded_bytes.decode("utf-8")

print(decoded_string)
# Output: Hello, World!

String Checking: You can check if a string starts or ends with a specific substring using the startswith() and endswith() methods.

s = "Hello, World!"
print(s.startswith("Hello"))
# Output: True

print(s.endswith("!"))
# Output: True

Methods that can be used to check characteristics of strings: In Python, there are several methods that can be used to check characteristics of strings, such as whether they consist of digits, alphabetic characters, alphanumeric characters, etc.

Get Dr. Pooja’s stories in your inbox

Join Medium for free to get updates from this writer.

isdigit(): This method returns True if all characters in the string are digits (0-9), and False otherwise.

num_s = "12345" 
print(num_s.isdigit())
# Output: True

alphanum_s = "abc123"
print(alphanum_s.isdigit())
# Output: False

isalpha(): This method returns True if all characters in the string are alphabetic characters (a-z or A-Z), and False otherwise.

alpha_s = "Hello" 
print(alpha_s.isalpha())
# Output: True

alphanum_s = "abc123"
print(alphanum_s.isalpha())
# Output: False

isalnum(): This method returns True if all characters in the string are either alphabetic characters or digits, and False otherwise.

ans = "abc123" 
print(ans.isalnum())
# Output: True

specialchar = "abc!@#"
print(specialchar.isalnum())
# Output: False

islower(): This method returns True if all cased characters in the string are lowercase, and False otherwise. It also returns False if the string contains non-letter characters.

lcs = "hello" 
print(lcs.islower())
# Output: True

mcs = "Hello"
print(mcs.islower())
# Output: False

isupper(): This method returns True if all cased characters in the string are uppercase, and False otherwise. It also returns False if the string contains non-letter characters.

ucs = "HELLO"
print(ucs.isupper())
# Output: True

mcs = "Hello"
print(mcs.isupper())
# Output: False

Strings are an essential and versatile data type in Python. They represent sequences of characters and allow you to work with textual data in various ways. Python provides a rich set of string methods that enable tasks such as changing case, splitting and joining strings, searching for substrings, and replacing characters and many more. Understanding strings and their features is crucial for effectively working with textual data in Python.

As you continue your Python journey, remember to refer to the Python documentation for a comprehensive list of string methods and their detailed usage.

Keep Learning!

--

--

Dr. Pooja
Dr. Pooja

Written by Dr. Pooja⁠

Academician, Mentor, Researcher - Artificial Intelligence | Data Science | Machine Learning | Data Analytics