⬅ Previous Topic
Python Data TypesNext Topic ⮕
Python Type Conversions⬅ Previous Topic
Python Data TypesNext Topic ⮕
Python Type ConversionsA 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.
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!"'
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."""
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
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
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
Python provides several built-in methods to work with strings:
lower()
: Converts all characters to lowercaseupper()
: Converts all characters to uppercasestrip()
: Removes leading and trailing whitespacereplace(old, new)
: Replaces substringsplit()
: Splits the string into a listjoin()
: Joins elements of a list with a string separators = " 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.
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.
msg = "Welcome to Python"
print("Python" in msg) # True
print("Java" not in msg) # True
for char in "Hi":
print(char)
H
i
text = "Python"
print(len(text)) # 6
Before working with strings, you might want to validate them:
isalpha()
– checks if all characters are alphabetsisdigit()
– checks if all characters are digitsisalnum()
– checks if all characters are alphanumericisspace()
– checks for only whitespaceval = "123abc"
print(val.isalnum()) # True
print(val.isdigit()) # False
+
for string concatenation. It's cleaner and faster.strip()
when reading user input to clean extra spaces.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!
***************
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.
⬅ Previous Topic
Python Data TypesNext Topic ⮕
Python Type ConversionsYou 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.