Python for Beginners (Working with Strings in Python)

Kalana De Silva
3 min readJun 7, 2024

--

Welcome back to our Python Programming series! In the previous article, we explored dictionaries and sets. Today, we’ll dive into strings, a fundamental data type in Python used for representing text. Let’s get started!

What is a String?

A string is a sequence of characters enclosed in single quotes, double quotes, or triple quotes.

# Single quotes
string1 = 'Hello, World!'

# Double quotes
string2 = "Hello, World!"

# Triple quotes (useful for multi-line strings)
string3 = '''Hello,
World!'''

Accessing Characters in a String

You can access individual characters in a string using indexing. Indexing starts from 0.

greeting = "Hello, World!"
print(greeting[0]) # Output: H
print(greeting[7]) # Output: W

Slicing Strings

Slicing allows you to get a substring from a string by specifying a start and end index.

greeting = "Hello, World!"
print(greeting[0:5]) # Output: Hello
print(greeting[7:12]) # Output: World

You can also use negative indices to slice from the end of the string.

print(greeting[-6:])  # Output: World!

String Methods

Python provides several built-in methods for working with strings.

len()

The len() function returns the length of a string.

print(len(greeting))  # Output: 13

lower() and upper()

The lower() method converts a string to lowercase, and the upper() method converts a string to uppercase.

print(greeting.lower())  # Output: hello, world!
print(greeting.upper()) # Output: HELLO, WORLD!

strip()

The strip() method removes any leading and trailing whitespace from a string.

whitespace_str = "   Hello, World!   "
print(whitespace_str.strip()) # Output: Hello, World!

replace()

The replace() method replaces all occurrences of a substring with another substring.

print(greeting.replace("World", "Python"))  # Output: Hello, Python!

split()

The split() method splits a string into a list of substrings based on a specified delimiter.

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

join()

The join() method joins a list of strings into a single string, with each element separated by a specified delimiter.

words = ["Hello", "World"]
print(" ".join(words)) # Output: Hello World

String Formatting

String formatting allows you to create strings with dynamic content.

Using format()

The format() method replaces placeholders in a string with specified values.

name = "Alice"
age = 25
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string) # Output: My name is Alice and I am 25 years old.

Using f-Strings

f-Strings (formatted string literals) provide a more concise way to format strings. They are available in Python 3.6 and later.

formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string) # Output: My name is Alice and I am 25 years old.

Escaping Characters

To include special characters in a string, you can use escape characters, preceded by a backslash \.

# Including quotes in a string
quote = "He said, \"Python is awesome!\""
print(quote) # Output: He said, "Python is awesome!"

# Including a backslash in a string
path = "C:\\Users\\Alice"
print(path) # Output: C:\Users\Alice

Multi-line Strings

Multi-line strings can be created using triple quotes.

multi_line_string = """This is a
multi-line
string."""
print(multi_line_string)
# Output:
# This is a
# multi-line
# string.

Summary

In this article, we learned about working with strings in Python. We covered how to create and access strings, use string methods, format strings, and handle special characters. Understanding strings is crucial for text processing and manipulation in your programs.

In the next article, we’ll explore file handling in Python, learning how to read from and write to files. Stay tuned for more Python fun every Monday, Wednesday, and Friday at 7 PM. Happy coding!

For real-time discussions, industry insights, and more, connect with me on LinkedIn. Let’s grow together!

🔗 Connect on LinkedIn

Thank you for being part of this learning journey!

--

--

Kalana De Silva

MERN | Laraval | Postman Student Expert | Full-Stack | Azure | Dev | IT Enthusiast | undergraduate at SLIIT