Python Strings


Python is one of the most popular programming languages today, and working with strings is a fundamental part of learning Python. Strings are sequences of characters used to store text, and understanding how to use them effectively is essential for any Python programmer.

In this tutorial, we will cover everything about Python strings, including how to create, manipulate, and work with them in practical ways. By the end, you will have a solid foundation to handle text in your Python programs.

What is a String in Python?

A string in Python is a sequence of characters enclosed in either single quotes '...', double quotes "...", or triple quotes '''...''' / """...""" for multi-line strings. Strings can include letters, numbers, symbols, and spaces.

Example:

name = "Emma"
greeting = 'Hello, how are you?'
description = """Python is a powerful programming language."""

In these examples:

  • name is a simple string.

  • greeting shows a sentence inside single quotes.

  • description uses triple quotes for a multi-line string.

Creating Strings in Python

You can create strings in multiple ways:

  1. Single Quotes:

single_quote_str = 'Python'
  1. Double Quotes:

double_quote_str = "Learning Python"
  1. Triple Quotes (Multi-line Strings):

multi_line_str = """Python is simple
and easy to learn."""
  1. Using str() function:
    You can also convert other data types into strings using the str() function.

number = 10
num_str = str(number)
print(num_str)  # Output: '10'

Accessing Characters in a String

Strings are indexed, which means each character has a position number starting from 0. You can access characters using square brackets [].

text = "Python"
print(text[0])  # Output: 'P'
print(text[3])  # Output: 'h'

You can also use negative indexing to access characters from the end:

print(text[-1])  # Output: 'n'
print(text[-3])  # Output: 'h'

Slicing Strings

Slicing allows you to extract a part of a string using start:stop:step syntax.

text = "PythonProgramming"
print(text[0:6])  # Output: 'Python'
print(text[6:])   # Output: 'Programming'
print(text[:6])   # Output: 'Python'
print(text[::2])  # Output: 'Pto rgamn' (every second character)

String Operations in Python

Python provides several operations to work with strings:

  1. Concatenation – combining two strings:

first = "Hello"
second = "World"
result = first + " " + second
print(result)  # Output: 'Hello World'
  1. Repetition – repeating a string multiple times:

text = "Python! "
print(text * 3)  # Output: 'Python! Python! Python! '
  1. Membership – checking if a substring exists in a string:

text = "Python is fun"
print("Python" in text)   # Output: True
print("Java" not in text) # Output: True

Common String Methods

Python strings have built-in methods that make text manipulation easier:

  • Changing Case:

text = "python"
print(text.upper())  # Output: 'PYTHON'
print(text.lower())  # Output: 'python'
print(text.title())  # Output: 'Python'
  • Removing Whitespace:

text = "   Python   "
print(text.strip())  # Output: 'Python'
  • Replacing Text:

text = "I like Java"
new_text = text.replace("Java", "Python")
print(new_text)  # Output: 'I like Python'
  • Splitting and Joining Strings:

text = "Python is easy"
words = text.split()  # ['Python', 'is', 'easy']
joined_text = "-".join(words)
print(joined_text)    # Output: 'Python-is-easy'
  • Finding and Counting:

text = "Python programming"
print(text.find("programming"))  # Output: 7
print(text.count("o"))           # Output: 2

String Formatting

Python allows you to insert values into strings using formatting:

  1. Using f-strings (Python 3.6+):

name = "Emma"
age = 25
print(f"My name is {name} and I am {age} years old.")
# Output: 'My name is Emma and I am 25 years old.'
  1. Using format() method:

text = "My name is {} and I am {} years old.".format("Emma", 25)
print(text)
  1. Using % operator:

text = "My name is %s and I am %d years old." % ("Emma", 25)
print(text)

Escape Characters in Strings

Sometimes, you need to include special characters in a string using the backslash \:

  • \n – Newline

  • \t – Tab

  • \\ – Backslash

  • \' – Single quote

  • \" – Double quote

text = "Hello\nWorld"
print(text)
# Output:
# Hello
# World

Strings are Immutable

One important property of strings in Python is that they are immutable. This means you cannot change a character in a string directly.

text = "Python"
# text[0] = "J"  # This will raise an error
new_text = "J" + text[1:]
print(new_text)  # Output: 'Jython'

Practical Examples with Strings

  1. Reversing a string:

text = "Python"
print(text[::-1])  # Output: 'nohtyP'
  1. Checking palindrome:

word = "level"
if word == word[::-1]:
    print("Palindrome")
else:
    print("Not Palindrome")
  1. Counting words in a sentence:

sentence = "Python is simple and powerful"
words = sentence.split()
print(len(words))  # Output: 5

Summary of the Tutorial

Python strings are powerful tools for handling text. They are easy to create, access, manipulate, and format. By learning string operations, slicing, and methods, you can handle almost any text-related task in Python. Strings are everywhere in programming, from user input to file processing, making them essential for every Python developer.

Mastering strings will give you a strong foundation for moving on to lists, tuples, dictionaries, and more advanced Python concepts.


Practice Questions

  1. Create a string variable city with the value "Paris" and print it.

  2. Given the string word = "Python", print the first and last characters using indexing.

  3. Using the string text = "Programming", extract and print only the first 6 characters.

  4. Combine the strings "Hello" and "World" with a space in between and print the result.

  5. Print the string "Ha" 5 times in a single line.

  6. Convert the string "python programming" to title case so that the first letter of each word is capitalized.

  7. In the string "banana", count how many times the letter "a" appears.

  8. Use an f-string to print: "My favorite language is Python" where "Python" is stored in a variable.

  9. Print the following on separate lines using a single string and escape characters:

    Line 1
    Line 2
    
  10. Write a program that takes a string input from the user and prints "Palindrome" if the string reads the same backward, otherwise prints "Not Palindrome".


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top