Table of Contents
What is a Python String?
A string is a sequence of characters enclosed in single quotes (' '), double quotes (" ") or even triple quotes (''' ''' or """ """) for multi-line text. Strings are used everywhere from storing names and messages to manipulating text data in real-world applications like chatbots, file handling or web scraping.
It is one of the most fundamental data types in Python. It is used in almost every program irrespective of whether you’re:
- Printing messages
- Reading user input
- Parsing data
- Or even generating reports
That’s why mastering string operations is essential for becoming a confident Python programmer.
Consider a few examples below.
name = "Riya Elizabeth"
greeting = 'Hello, world!'
paragraph = """This is
a multi-line
string."""
Accessing the String Items
Indexing:
Indexing is the process of retrieving a single character from a string by referencing its specific numerical position (its index).
Strings are ordered sequences, meaning each character has a fixed, zero-based index.
Formula/Rule (Accessing): The syntax is string{index}.
Positive indices start at 0 for the first character.
Negative indices start at -1 for the last character.
Looping Through a String
Looping is the process of accessing and processing every single item in a string sequentially until the end of the string is reached.
This is typically done using a
forloop.
Consider the example program below.
my_string = "Example"
print(f" {my_string[0]}") # E
print(f" {my_string[3]}") # m
print(f" {my_string[-1]}") # e
# Looping through the String
for char in my_string:
print(f"Character: {char}")
# Character: E
# Character: x
# Character: a
# Character: m
# Character: p
# Character: l
# Character: e
Basic String Operations in Python
Let’s dive into the most common and powerful string operations.
1. String Concatenation (Join)
String concatenation is used to join two or more strings. We use the (+) operator to concatenate strings.
Write a Python program to concatenate two strings.
first_name = "Riya"
last_name = "Elizabeth"
full_name = first_name + last_name
print(full_name)
# Output: RiyaElizabeth
Analysis:
The two strings “Riya” and “Elizabeth” are assigned to the variables first_name and last_name respectively.
full_name = first_name + last_name: This line uses addition operation (+) to join the strings together and assigns it to full_name.
2. Repetition
Use the ‘*’ operator to repeat a string multiple times.
Write a python program to print “Hi!” three times using String Repetition.
print("Hi! " * 3)
# Output: Hi! Hi! Hi!
Analysis:
Hi! *3 = Hi! hi! hi!
3. Indexing
Indexing is used to access an individual character of a string using index values starting from 0.
Positive Indexing: Indexing starts from 0 for the first character.
Negative Indexing: Counts backward from the end of the string. Index -1 refers to the last character ‘n’.
Write a Python program to access individual characters from the string using Indexing.
word = "Python"
print(word[0]) # Output: P
print(word[-1]) # Output: n
Analysis:
(word[0]) refers to the first character P.
(word[-1]) Here -1 counts backward from the end of the string and hence refers to n.
4. Slicing
String slicing in Python is used to extract a segment or a substring from a larger string. [:] symbol is used to extract the substring. It uses index numbers starting from 0 for the first character.
Write a Python program to perform string indexing.
text = "Hello, Python!"
print(text[0:5]) # Output: Hello
print(text[7:]) # Output: Python!
print(text[:5]) # Output: Hello
Analysis:
“Hello, Python is the string.
print(text[0:5]): Indexing starts at the first character H and ends before the sixth character (comma).
print(text[7:]): Indexing starts at the seventh character P and goes all the way to the end of the string.
print(text[:5]): Indexing starts at the beginning character and stops before the index 5.
Python String Methods
Python provides dozens of built-in string methods to make your life easier. Let’s explore the most popular ones:
| Method | Description |
|---|---|
| upper() | Converts all characters in the string to uppercase. |
| lower() | Converts all characters in the string to lowercase. |
| title() | Converts the first character of every word to uppercase and the rest to lowercase. |
| strip() | Removes any leading (start) and trailing (end) whitespace characters. |
| replace(a,b) | Replaces all occurrences of the first substring with the second substring. |
| split() | Splits the string into a list of substrings wherever the comma (",") is found. |
| join() | Joins the elements of a list together, using the string (“-“) as the separator. |
| find() | Returns the index (position) of the first occurrence of the specified substring. |
| count() | Counts occurrences of specified character or substring. |
| len() | Gives the number of characters in the string. (Includes whitespaces and all characters) |
print('hello'.upper()) # HELLO
print('HELLO'.lower()) # hello
print('python programming'.title()) # Python Programming
print(' hello '.strip()) # hello
print('I like Java'.replace('Java', 'Python')) # I like Python
print('a,b,c'.split(',')) # ['a', 'b', 'c']
print('-'.join(['a', 'b', 'c'])) # a-b-c
print('hello'.find('e')) # 1
print('banana'.count('a')) # 3
print(len('qubrica')) # 7
String Formatting in Python
String formatting in Python is the process of creating a new string by embedding values of variables or expressions into a fixed template string.
1. Using f-Strings:
An f-string (formatted string literal) is simply the easiest and fastest way to mix Python variables and code directly into a piece of text. An f-string lets you write your sentence naturally and just put the variable’s name inside curly braces ({ }).
Consider an example below
name = "Riya"
age = 20
print(f"My name is {name} and I am {age} years old.")
# output: My name is Riya and I am 20 years old.
2. Using format() Method:
This method uses curly braces ({}) as placeholders within a string, which are then filled by arguments passed to the .format() method at runtime. It offers flexibility in ordering and reuse of values.
Take a look at the example below
msg = "My name is {} and I love {}".format("Riya", "Python")
print(msg)
# output: My name is Riya and I love Python.
3. Using Percent Formatting
An older C-style method where values are inserted into a string using the modulo operator (%) and format specifiers (like %s for string, %d for integer). It’s generally discouraged in new Python code.
Consider the example below
name = "Riya"
print("Hello, %s!" % name)
# output: Hello, Riya!
FAQ (Frequently Asked Questions)
1. How to clone a string in Python?
A string can be cloned (copied) by either using a direct assignment or a string slicing method.
s1 = “hello”
s2 = s1[:]
s3 = s1
print(f”s2: {s2}”)
print(f”s3: {s3}”)
s2 = s1[:] #creates a new string with the same content.
2. How to convert int to a string?
We can use the built-in str() function:
s = str(123) # ‘123’
3. How to find the length of a string in Python?
We can use a simple len() function
len(Python) # 6
4. How to reverse a string in Python?
We can reverse a string by using slicing technique with -1.
“hello”[::-1] # ‘olleh’
5. What arithmetic operators cannot be used with strings in Python?
You cannot use -, *(with another string), /, //, or % with strings.
Only + (concatenation) and *(with int for representation) can be used.
6. What does b-string mean in Python?
A b string (b”hello”) represents a byte string. Data is represented in bytes instead of text (used for binary data).
7. How to concatenate strings in Python?
The + operator or the join method can be used to concatenate strings. “Hello” + ” World” # ‘Hello World’
8. Are strings mutable in Python?
No strings are immutable. Once created the content cannot be changed.
9. How to convert a string to float in Python?
By using the float function a string can be converted to float
num = float(“12.5”) # 12.5