Python Strings
Basics and Examples

What is a String in Python?

A string in Python is a sequence of characters enclosed in single ('), double ("), or triple quotes (''' or """).

'Hello, World!'
"Hello, World!"

Strings are used to store text-based information such as names, messages, or any human-readable data.

Creating Strings

You can create a string using single or double quotes interchangeably:

name = 'Arjun'
message = "Hello, World!"

If your string contains quotes inside, use the other type to avoid syntax errors:

quote = "It's a beautiful day"
alt_quote = 'He said, "Hi!"'

Multiline Strings

Use triple quotes when you want to write strings across multiple lines.

poem = """Roses are red,
Violets are blue,
Python is great,
And so are you."""

Accessing Characters in a String

In Python, you can access individual characters in a string using indexing. Each character in the string has a position, called an index, which starts from 0 for the first character and increases by one for each subsequent character.

Here's how you can use positive indexing to access characters from the beginning:

greeting = "Hello"
print(greeting[0])  # H (first character)
print(greeting[4])  # o (fifth character)
H
o

Python also supports negative indexing, which allows you to access characters from the end of the string. The last character has an index of -1, the second last is -2, and so on.

greeting = "Hello"
print(greeting[-1])  # o (last character)
print(greeting[-2])  # l (second last character)
o
l

This flexibility makes it easy to access both ends of a string without needing to know its exact length.

String Slicing

Slicing helps extract parts of a string using the syntax string[start:end].

text = "Python"
print(text[0:2])   # Py
print(text[2:])    # thon
print(text[:3])    # Pyt
print(text[-3:])   # hon
Py
thon
Pyt
hon

Immutability of Strings

Strings in Python are immutable. This means once created, they cannot be changed in place.

word = "Python"
word[0] = "J"  # This will raise a TypeError
Traceback (most recent call last):
  File "main.py", line 2, in 
    word[0] = "J"  # This will raise a TypeError
TypeError: 'str' object does not support item assignment

Common String Methods

Python provides several built-in methods to work with strings:

  • lower(): Converts all characters to lowercase
  • upper(): Converts all characters to uppercase
  • strip(): Removes leading and trailing whitespace
  • replace(old, new): Replaces substring
  • split(): Splits the string into a list
  • join(): Joins elements of a list with a string separator
s = "  Learn Python  "
print(s.strip())        # 'Learn Python'
print(s.lower())        # '  learn python  '
print(s.replace("Python", "Java"))  # '  Learn Java  '
Learn Python
  learn python  
  Learn Java  

For complete set of string methods in Python, you may refer String methods.

String Formatting

In Python, you can insert variables directly into strings using f-strings (formatted string literals). This makes it easy to construct readable and dynamic messages.

name = "Arjun"
age = 25
print(f"My name is {name} and I am {age} years old.")
My name is Arjun and I am 25 years old.

Checking Substrings

Python allows you to check whether a certain substring exists within a string using the in and not in keywords. These return a boolean value — True or False.

msg = "Welcome to Python"
print("Python" in msg)     # True, because "Python" is in the string
print("Java" not in msg)   # True, because "Java" is not in the string
True
True

Looping Through a String

Since strings are sequences of characters, you can loop through them using a for loop. Each iteration gives you one character from the string.

for char in "Hi":
    print(char)
H
i

Length of a String

You can find out how many characters are in a string using the built-in len() function. This includes letters, digits, spaces, and symbols.

text = "Python"
print(len(text))  # 6
6

Validation & Checks

Before working with strings, you might want to validate them:

  • isalpha() – checks if all characters are alphabets
  • isdigit() – checks if all characters are digits
  • isalnum() – checks if all characters are alphanumeric
  • isspace() – checks for only whitespace
val = "123abc"
print(val.isalnum())  # True
print(val.isdigit())  # False
True
False

Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...