DEV Community

yuna song
yuna song

Posted on

Python Basics: Strings

1. String Basics

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

Common Operations

text = "Python"

text + " Basics"      # Concatenate strings
text * 3              # Repeat a string
len(text)             # String length
Enter fullscreen mode Exit fullscreen mode

2. Escape Sequences

Escape sequences represent special characters inside strings.

Escape Description
\n New line
\t Horizontal tab
\\ Backslash (\)
\' Single quote
\" Double quote
\r Carriage return
\f Form feed
\a Bell (alert)
\b Backspace
\0 Null character

Example:

print("Hello\nWorld")
Enter fullscreen mode Exit fullscreen mode

3. String Slicing

Extract part of a string using indexes.

Syntax

string[start:end]
Enter fullscreen mode Exit fullscreen mode
  • start is inclusive.
  • end is exclusive.

Example:

text = "Python"

text[0:2]      # "Py"
text[:4]       # "Pyth"
text[2:]       # "thon"
text[-1]       # "n"
Enter fullscreen mode Exit fullscreen mode

4. String Formatting

% Formatting (Legacy)

"%s" % "Python"
"%d" % 10
"%.2f" % 3.14159
Enter fullscreen mode Exit fullscreen mode

Common format specifiers:

Code Description
%s String
%c Character
%d Integer
%f Float
%o Octal
%x Hexadecimal
%% Percent sign

str.format()

"Hello, {}".format("Python")
"{0} {1}".format("Hello", "World")
"{name}".format(name="Python")
Enter fullscreen mode Exit fullscreen mode

Alignment:

"{:<10}".format("Hi")     # Left
"{:>10}".format("Hi")     # Right
"{:^10}".format("Hi")     # Center
"{:*^10}".format("Hi")    # Fill with *
Enter fullscreen mode Exit fullscreen mode

Floating-point precision:

"{:.2f}".format(3.14159)
Enter fullscreen mode Exit fullscreen mode

Escape braces:

"{{Python}}"
Enter fullscreen mode Exit fullscreen mode

f-Strings (Recommended)

Available in Python 3.6+.

name = "Python"
version = 3.13

f"{name} {version}"
f"{version:.1f}"
f"{name:>10}"
Enter fullscreen mode Exit fullscreen mode

Supports:

  • Variables
  • Expressions
  • Dictionary access
  • Alignment
  • Number formatting

Example:

x = 10
y = 20

f"{x} + {y} = {x + y}"
Enter fullscreen mode Exit fullscreen mode

5. Common String Methods

Search

text.count("a")
text.find("a")
text.index("a")
Enter fullscreen mode Exit fullscreen mode
  • count() : Count occurrences.
  • find() : Return index, or -1 if not found.
  • index() : Return index, or raise ValueError.

Case Conversion

text.upper()
text.lower()
Enter fullscreen mode Exit fullscreen mode

Remove Whitespace

text.strip()
text.lstrip()
text.rstrip()
Enter fullscreen mode Exit fullscreen mode

Replace

text.replace("Python", "Java")
Enter fullscreen mode Exit fullscreen mode

Split

text.split()
text.split(",")
Enter fullscreen mode Exit fullscreen mode

Returns a list of substrings.

Join

",".join(["A", "B", "C"])
Enter fullscreen mode Exit fullscreen mode

Output:

A,B,C
Enter fullscreen mode Exit fullscreen mode

Notes

  • Strings are immutable, meaning their contents cannot be changed directly.
  • Most string methods return a new string instead of modifying the original.

Note: AI was used to assist in the drafting and formatting of this post.

Top comments (0)