Sitemap
Sameenah Tm

Sameenah Tm

Python Strings

What is a String?

  • A string is a sequence of characters in Python
  • Strings can include letters, numbers, symbols, and spaces.
  • Strings are immutable, meaning you cannot change a character directly once the string is created.

Strings are defined as follows:

single_quotes = ‘Hello’
double_quotes = “World”
triple_quotes = ‘’’Multiline
String’’’

s is a string and s = “Hello, World!”

len(s) # 13 → number of characters
s[0] # ‘H’ → first character
s[-1] # ‘!’ → last character
s[0:5] # ‘Hello’ → slicing
s[:5] # ‘Hello’ → from start to index 5
s[7:] # ‘World!’ → from index 7 to end
s[::-1] # ‘!dlroW ,olleH’ → reverse string

String Methods

There are a lot of methods. But we usually use a couple of methods and those methods are listed below with a description.

MethodDescription

lower() Converts to lowercase > "HELLO".lower() >"hello"

upper() Converts to uppercase"hello".upper() > “HELLO”

title()Capitalizes first letter of each word"hello world".title() → “Hello World"

capitalize() Capitalizes the first character "hello".capitalize() → “Hello”

strip().Removes whitespace from both ends" hello ".strip() → “hello”

lstrip()Removes left whitespace" hello".lstrip() → “hello”

rstrip()Removes right whitespace"hello ".rstrip() → “hello”

split(sep=None)Splits string into list"a,b,c".split(",") → [‘a’,’b’,’c’]

join(iterable)Joins iterable into string"-".join(["a","b"]) → "a-b"

replace(old, new)Replace substring"hello".replace("l","L") → “heLLo”

find(sub)Find substring index (-1 if not found) "hello".find("l") → 2 count(sub)Count occurrences"hello".count("l") -> 2

startswith(prefix)Check start"hello".startswith("he") → True

Get Sameenah Tm’s stories in your inbox

Join Medium for free to get updates from this writer.

endswith(suffix)Check end"hello".endswith("lo") → True

isalnum()Check alphanumeric"abc123".isalnum() → True

isalpha()Check letters only"abc".isalpha() → True

isdigit()Check digits only"123".isdigit() → True

isspace()Check whitespace" ".isspace() → True

String Formatting

f-Strings Availabe on the version of Python 3.6+

Example:

name = "Alice"
age = 25
f"Name: {name}, Age: {age}" # "Name: Alice, Age: 25"

format() Method

"Name: {}, Age: {}".format("Alice", 25)   # "Name: Alice, Age: 25"

String Membership & Iteration

s = "Python"

"P" in s # True
"x" not in s # True

for char in s:
print(char)

Concatenation & Repetition

a = "Hello"
b = "World"

a + " " + b # "Hello World"
a * 3 # "HelloHelloHello"

Slicing Shortcuts

s = "abcdefgh"

s[2:5] # "cde" → index 2 to 4
s[:3] # "abc" → start to 2
s[3:] # "defgh" → 3 to end
s[::2] # "aceg" → every second character
s[::-1] # "hgfedcba" → reverse string

Converting Between Strings & Other Types

str(123)        # "123"
int("456") # 456
float("3.14") # 3.14
list("abc") # ['a','b','c']

Summary:

Strings are immutable sequences of characters

Use methods like split, join, replace, lower, upper for most operations

Use slicing and indexing to access parts of a string

Use f-strings or format for dynamic content

Escape sequences handle special characters like newline and tab

--

--