Python Strings
Python strings are a collection of characters that are wrapped in double quotes ("") or single quotes (' '). For instance, "hello" is a string that holds a series of characters 'h', 'e', 'l', 'l', 'o.
# Double Quotes
str1 =
"Hello Python"
# Single quotes
str2 =
'Hello Python'
Example:
str1 =
"Hello Python"
print(str1)
Output
Hello Python
Access String Characters
Example:
str1 =
"Python"
print(str1[2])
Output
t
Python String Operations
Compare Two Strings
We use the == operator to compare two strings.
Example:
str1 =
"Hello Python"
str2 =
"I love Python"
str3 =
"Hello Python"
print(str1
== str2)
print(str1
== str3)
Output
False
True
String Concatenation
To combine two or more strings, you can use the + operator.
Example:
str1 =
"Hello"
str2 =
" World"
result = str1 + str2
print(result)
Output
Hello World
String Length
To get the length of a string, use the len() function.
Example:
str1 =
"Hello Python"
print(len(str1))
Output
12
String Methods
JavaScript provides a number of built-in methods for handling strings.
upper()
The upper() method makes a string upper case.
Example:
str1 =
"Hello Python"
print(str1.upper())
Output:
HELLO PYTHON
lower()
The lower() method in Python is a pre-programmed string method that translates all the capital characters in a string into lower cases.
Example:
str1 =
"Hello Python"
print(str1.lower())
Output:
hello python
replace
The replace() function substitutes a string with another string.
Example:
str1 =
"Hello Python"
print(str1.replace("Python", "World"))
Output:
Hello World