DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Python Strings Explained Simply (Common Operations and Methods)

Strings are used to handle text in Python. They are one of the most common data types and come with many built-in tools.

What is a string?

A string is text enclosed in single quotes ' ' or double quotes " ".

name = "Alex"
message = 'Hello, Python!'
multiline = """This is a
multi-line string."""
Enter fullscreen mode Exit fullscreen mode

Strings are immutable, which means you cannot change them directly. Operations create new strings instead.

Basic operations

Concatenate (join) strings with +:

greeting = "Hello" + " " + "Alex"
print(greeting)  # Hello Alex
Enter fullscreen mode Exit fullscreen mode

Repeat a string with *:

stars = "*" * 10
print(stars)  # **********
Enter fullscreen mode Exit fullscreen mode

Get the length with len():

print(len(name))  # 4
Enter fullscreen mode Exit fullscreen mode

Accessing characters

Use indexes to get individual characters. Indexes start at 0.

text = "Python"

print(text[0])  # P
print(text[-1]) # n (last character)
Enter fullscreen mode Exit fullscreen mode

Slice to get a substring:

print(text[1:4])  # yth
print(text[:3])   # Pyt (from start)
print(text[3:])   # hon (to end)
Enter fullscreen mode Exit fullscreen mode

Common string methods

Convert case:

text = "hello python"

print(text.upper())   # HELLO PYTHON
print(text.lower())   # hello python
print(text.title())   # Hello Python
Enter fullscreen mode Exit fullscreen mode

Replace parts:

message = "I like cats"
new_message = message.replace("cats", "dogs")
print(new_message)  # I like dogs
Enter fullscreen mode Exit fullscreen mode

Split into a list:

words = "apple,banana,cherry"
word_list = words.split(",")
print(word_list)  # ['apple', 'banana', 'cherry']
Enter fullscreen mode Exit fullscreen mode

Check content:

email = "user@example.com"

print(email.startswith("user"))  # True
print(email.endswith(".com"))    # True
Enter fullscreen mode Exit fullscreen mode

Formatting strings

Use f-strings for clean formatting:

name = "Alex"
age = 25

print(f"{name} is {age} years old.")  # Alex is 25 years old.
Enter fullscreen mode Exit fullscreen mode

Common mistake: trying to change a string directly

Strings are immutable, so this causes an error:

text = "hello"
text[0] = "H"  # TypeError: 'str' object does not support item assignment
Enter fullscreen mode Exit fullscreen mode

Create a new string instead:

new_text = "H" + text[1:]
print(new_text)  # Hello
Enter fullscreen mode Exit fullscreen mode

Quick summary

  • Create strings with quotes.
  • Use indexing and slicing to access parts.
  • Apply methods like .upper(), .lower(), .replace(), and .split().
  • Use f-strings for easy formatting.
  • Remember strings are immutable.

Practice common operations on strings. They are essential for handling text in Python programs.

Top comments (0)