Yandex

Python Strings
Basics with Examples



What is a String in Python?

A string in Python is a sequence of characters enclosed in single ('), double ("), or triple quotes (''' or """). 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 = 'Alice'
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

Python allows indexing, where each character in a string has a position (index). Indexes start from 0.

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

You can also use negative indexing:

print(greeting[-1])  # o
print(greeting[-2])  # l

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

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

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  '

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

String Formatting

You can inject variables into strings using f-strings (formatted string literals):

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

Checking Substrings

msg = "Welcome to Python"
print("Python" in msg)     # True
print("Java" not in msg)   # True

Looping Through a String

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

Length of a String

text = "Python"
print(len(text))  # 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

Tips for Beginners

  • Use f-strings over + for string concatenation. It's cleaner and faster.
  • Watch out for off-by-one errors in slicing.
  • Use strip() when reading user input to clean extra spaces.
  • Remember: Strings are case-sensitive in comparisons.

Practice Exercise

Try writing a small program that takes a name input and returns a welcome message in uppercase with a border:

name = input("Enter your name: ").strip()
message = f"Welcome, {name.upper()}!"
border = "*" * len(message)
print(border)
print(message)
print(border)
Enter your name: Arjun
***************
Welcome, ARJUN!
***************

Conclusion

Strings are the heart of text processing in Python. From basic print statements to complex NLP tasks, strings are foundational. With the tools and checks you've learned here, you're ready to explore more sophisticated operations and integrations in Python development.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M