coding180 icon
Coding180
Learn Python Strings: Indexing, Slicing, Methods & Formatting

Learn Python Strings: Indexing, Slicing, Methods & Formatting

Home > Tutorials > Python for beginners > Data structure


If you're new to programming, learning how to work with strings is a great place to start. Strings are one of the fundamental data types in Python and are used to represent text. In this guide, we'll cover everything you need to know to get started with strings in Python, including indexing, slicing, string methods, and string formatting.

What Are Strings?

In Python, strings are sequences of characters enclosed in either single or double quotes. Here's an example:

my_string = "Hello, World!"

In this case, my_string is a string that contains the text "Hello, World!".

Strings can be assigned to variables just like any other data type, and they can be concatenated (joined together) using the + operator. Here's an example:

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)

This code will output John Doe, which is the result of concatenating the first_name and last_name strings with a space in between.

Indexing and Slicing

Strings in Python are indexed, which means that each character in the string has a unique position represented by an integer index. The first character in a string has an index of 0, the second character has an index of 1, and so on.

To access individual characters in a string, you can use indexing. Here's an example:

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

In this case, we're using indexing to access the first and eighth characters in the string.

You can also use slicing to access a range of characters within a string. Slicing is done by specifying two indices separated by a colon (:). Here's an example:

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

In this case, we're using slicing to extract the first five characters in the string.

String Methods

Python provides a number of built-in methods for working with strings. These methods can be used to perform common tasks like converting a string to uppercase or lowercase, finding the length of a string, replacing part of a string with new text, and much more.

Here are some examples of common string methods in Python:

upper()

Converts all the characters in a string to uppercase.

my_string = "Hello, World!"
print(my_string.upper()) # Output: HELLO, WORLD!

lower()

Converts all the characters in a string to lowercase.

my_string = "Hello, World!"
print(my_string.lower()) # Output: hello, world!

replace()

Replaces all occurrences of one substring in a string with another substring.

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

split()

Splits a string into a list of substrings based on a delimiter.

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

String Formatting

String formatting is a way of inserting variables or values into a string. Python provides several ways to format strings, including using the % operator and the format() method.

Here are some examples of string formatting in Python:

Using the % Operator

name = "John"
age = 30
print("My name is %s and I'm %d years old." % (name, age)) 
# Output: My name is John and I'm 30 years old.

In this case, we're using the % operator to insert the values of the name and age variables into the string.

Using the format() Method

name = "John"
age = 30
print("My name is {} and I'm {} years old.".format(name, age)) 
# Output: My name is John and I'm 30 years old.

In this case, we're using the format() method to insert the values of the name and age variables into the string.

Exercises

Now that you understand the basics of working with strings in Python, it's time to practice with some exercises. Don't worry if you don't get everything right on the first try - programming is all about trial and error!

Exercise 1

Write a program that prompts the user to enter their name and then prints a greeting that includes their name.

name = input("What is your name? ")
print("Hello, {}!".format(name))

In this code, we're using the input() function to prompt the user to enter their name, and then using the format() method to insert their name into the greeting string.

Exercise 2

Write a program that prompts the user to enter a phrase and then prints the phrase in reverse.

phrase = input("Enter a phrase: ")
reversed_phrase = phrase[::-1]
print(reversed_phrase)

In this code, we're using slicing to reverse the order of the characters in the phrase string.

Exercise 3

Write a program that prompts the user to enter a sentence and then counts the number of words in the sentence.

sentence = input("Enter a sentence: ")
word_count = len(sentence.split())
print("The sentence has {} words.".format(word_count))

In this code, we're using the split() method to split the sentence string into a list of individual words, and then using the len() function to count the number of items in the list.

Conclusion

In this guide, we've covered the basics of working with strings in Python. We've learned how to index and slice strings, use built-in string methods, and format strings using variables and values. With a little practice, you'll be able to use these concepts to build more complex programs and applications. Keep coding!


user

Robort Gabriel

Lagos, Nigeria

Freelance Web Developer, Native Android Developer, and Coding Tutor.

Skills
  • UI / UX
  • JavaScript
  • Python
  • PHP
  • Kotlin
  • Java
  • Bootrap
  • Android
  • Laravel