Strings are one of the fundamental data types in Python, used to represent textual data. They are sequences of characters and allow developers to work with textual information in a flexible and powerful way. In this lesson, we will explore the basics of Python strings, their operations, manipulation, and some useful methods.
Creating Strings
In Python, you can create strings by enclosing characters in either single quotes (') or double quotes (").
single_quoted_str = 'Hello, Python!'
double_quoted_str = "Strings are fun!"
Both single_quoted_str and double_quoted_str are valid strings in Python and produce the same output.
You can also create multi-line strings using triple single or double quotes;
multi_line_str = '''
This is a multi-line
string in Python.
'''
String Operations
Python supports various operations on strings that make it easy to manipulate and work with textual data.
1. Concatenation
You can concatenate two or more strings using the +
operator.
str1 = 'Hello'
str2 = 'SomeQuiz'
result = str1 + ', ' + str2
print(result)
- Output:
'Hello, SomeQuiz'
2. Repetition
You can repeat a string multiple times using the *
operator.
str1 = 'Hello'
result = str1 * 3
print(result)
- Output:
'HelloHelloHello'
3. Membership
You can check if a substring exists within a string using the in
or not in
operators.
my_string = 'Hello, SomeQuiz'
print('Hello' in my_string)
print('Python' not in my_string)
- Output:
True
True
String Methods
Python provides a rich set of built-in methods to perform various operations on strings. Here are some commonly used string methods;
Method | description |
---|---|
lower() | These method return a new string with all characters converted to lowercase |
upper() | These method return a new string with all characters converted to uppercase |
strip() | This method removes leading and trailing whitespace characters from a string. |
replace() | This method replaces all occurrencesof a specified substring with another substring. |
find() and index() | These methods search for a substring within a string and return the index of the first occurrence. However, find() returns -1 if the substring is not found, while index() raises an exception. |
startswith() and endswith() | These methods check if a string starts or ends with a specified substring and return a Boolean value. |
join() | This method concatenates a list of strings with a specified delimiter. |
isdigit() and isalpha() | These methods check if a string contains only digits or alphabetic characters, respectively. |
📎 lower()
- Syntax
text = "HELLO@SOMEQUIZ.Space"
x = text.lower()
print(x)
- Output:
hello@somequiz.space
📎 upper()
- Syntax
text = "Hello coders!"
x = text.upper()
print(x)
- Output:
HELLO CODERS!
📎 strip()
-
Syntax
-
Without Parameter
text = " somequiz "
x = text.strip()
print("hello@" + x + ".space")
- Output
hello@somequiz.space
-
Syntax
-
With Parameter
text = "...somequiz,,,,"
x = text.strip('.,')
print("hello@" + x + ".space")
hello@somequiz.space
📎 replace()
-
Syntax
-
Without Count Parameter
text = "Welcome to w3schcools"
x = text.replace("w3schcools", "SomeQuiz")
print(x)
- Output
Welcome to SomeQuiz
-
With Count Parameter
-
Syntax
msg = 'Hello there......'
x = msg.replace("." ,"!", 3)
print(x)
- Output
hello there!!!...
📎find()
The find() method finds the first occurrence of the specified value.
The find() method returns -1 if the value is not found.
- Syntax
- Without Starting Index and Ending Indexes
text = "Hello, welcome to SomeQuiz."
x = text.find("o") # Where in the text is the first occurrence of the letter "e"?
y = text.find("o", 10, 15) # Where in the text is the first occurrence of the letter "e"
# when you only search between position 10 and 15
z = text.find("x") # value is not found
print(x)
print(y)
print(Z)
- output
4
11
-1
📎index()
The index()
method raises an exception if the value is not found.
The index()
method is almost the same as the find()
method, the only difference is that the find()
method returns -1 if the value is not found.
- Syntax
txt = "Hello, welcome to SomeQuiz."
print(txt.index("e"))
print(txt.index("e", 5, 10))
print(txt.index("x"))
- Output
1
8
Traceback (most recent call last):
File "c:\Users\nuwan\Documents\developments\python-database\main.py", line 27, in <module>
print(txt.index("x"))
ValueError: substring not found
📎 startswith()
- Syntax
txt = "Hello, welcome to SomeQuiz."
x = txt.startswith("wel", 7, 20)
print(x)
- Output
True
📎 endswith()
- Syntax
txt = "Hello, welcome to SomeQuiz."
x = txt.endswith("Quiz.")
print(x)
- Output
True
📎 join()
- Syntax
myTuple = ("Sithija", "Ashwin", "Venul")
x = " | ".join(myTuple)
print(x)
- Output
Sithija | Ashwin | Venul
📎 isdigit()
a = "\u0030" #unicode for 0
b = "5623"
c= "gfd"
print(a.isdigit())
print(b.isdigit())
print(c.isdigit())
- Output
True
True
False
📎isalpha()
text_1 = "H311o"
text_2 = "SomeQuiz"
print(text_1.isalpha())
print(text_2.isalpha())
- Output
False
True
These are just a few examples of the many string methods available in Python.
String Formatting
String formatting is a powerful feature in Python that allows you to create dynamic strings by inserting variable values into placeholders within a string. There are multiple ways to achieve string formatting in Python, including the older % operator and the newer format() method.
name = 'Peter'
age = 20
greeting = 'Hello, my name is {} and I am {} years old.'.format(name, age)
print(greeting)
- Output
Hello, my name is Peter and I am 20 years old.
In Python 3.6 and above, you can also use f-strings, which provide a concise and readable way to format strings using embedded expressions.
name = 'John'
age = 25
greeting = f'Hello, my name is {name} and I am {age} years old.'
print(greeting)
- Output
Hello, my name is John and I am 25 years old.
String formatting allows you to create dynamic and customized output based on variables, making your code more flexible and readable.
Strings are an essential component of Python programming, enabling developers to work with textual data efficiently. In this lesson, we covered the basics of creating and accessing strings, along with some common operations and methods. We also explored string formatting, which is a powerful technique for creating dynamic and customized output.