Strings
Strings
We use single quotes or double quotes to represent a string in Python. For example,
Here, we have created a string variable named string1 . The variable is initialized with
the string "Python Programming" .
Output
Python
I love Python.
In the above example, we have created string-type variables: name and message with
values "Python" and "I love Python" respectively.
Here, we have used double quotes to represent strings, but we can use single quotes
too.
Negative Indexing: Similar to a list, Python allows negative indexing for its
strings. For example,
greet = 'hello'
# access 4th last element
print(greet[-4]) # "e"
Note: If we try to access an index out of the range or use numbers other than an
integer, we will get errors.
Output
However, we can assign the variable name to a new string. For example,
message = 'Hola Amigos'
# assign new string to message variable
message = 'Hello Friends'
print(message); # prints "Hello Friends"
Output
In the above example, anything inside the enclosing triple quotes is one multiline string.
False
True
In the above example, we have used the + operator to join two strings: greet and name .
Output
H
e
l
l
o
Python String Length
In Python, we use the len() method to find the length of a string. For example
greet = 'Hello'
# count length of greet string
print(len(greet))
# Output: 5
Methods Description
string.upper()
Output
if(firstString.upper() == secondString.upper()):
print("The strings are same.")
else:
print("The strings are not same.")
Output
Example
message = 'PYTHON IS FUN'
# convert message to lowercase
print(message.lower())
# Output: python is fun
Syntax of String lower()
The syntax of lower() method is:
string.lower()
Output
if(firstString.lower() == secondString.lower()):
print("The strings are same.")
else:
print("The strings are not same.")
Output
string.partition(separator)
partition() Parameters()
The partition() method takes a string parameter separator that separates the string at
the first occurrence of it.
the part before the separator, separator parameter, and the part after the
separator if the separator parameter is found in the string
the string itself and two empty strings if the separator parameter is not found
print(string.partition('is '))
print(string.partition('is'))
Output
replace() Syntax
Its syntax is:
replace() Arguments
The replace() method can take a maximum of three arguments:
old - the old substring we want to replace
new - new substring which will replace the old substring
count (optional) - the number of times you want to replace the old substring with
the new string
Note: If count is not specified, the replace() method replaces all occurrences of
the old substring with the new string.
Output
Output
# Output: 12
If the substring exists inside the string, it returns the index of the first occurence
of the substring.
Output
Since strings are represented by single or double quotes, the compiler will treat "He
said, " as a string. Hence, the above code will cause an error.
To solve this issue, we use the escape character \ in Python.
# escape double quotes
example = "He said, \"What's there?\""
# escape single quotes
example = 'He said, "What\'s there?"'
print(example)
# Output: He said, "What's there?"
\\ Backslash
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
Output
Cathy is from UK
Python str()
The str() method returns the string representation of a given object.
Example
# string representation of Adam
print(str(5367))
# Output: 5367
Output
Luke
40
7ft
In the above example, we have used the str() method with different types of
arguments like string, integer, and numeric string.
f-strings
Python 3.6 added new string interpolation method called literal string interpolation and
introduced a new literal prefix f . This new way of formatting strings is powerful and
easy to use. It provides access to embedded Python expressions inside string
constants.
Example 1:
name = 'World'
program = 'Python'
In above example literal prefix f tells Python to restore the value of two string
variable name and program inside braces {} . So, that when we print we get the above
output.
This new string interpolation is powerful as we can embed arbitrary Python expressions
we can even do inline arithmetic with it.
Example 2:
a = 12
b = 3
12 multiply 3 is 36.
In the above program we did inline arithmetic which is only possible with this method.
%-formatting
Strings in Python have a unique built-in operation that can be accessed with
the % operator. Using % we can do simple string interpolation very easily.
Example 3:
Hello World
Example 4:
name = 'world'
program ='python'
In above example we used two string variable name and program . We wrapped both
variable in parenthesis () .
It’s also possible to refer to variable substitutions by name in our format string, if we
pass a mapping to the % operator:
Example 5:
name = 'world'
program ='python'
This makes our format strings easier to maintain and easier to modify in the future. We
don’t have to worry about the order of the values that we’re passing with the order of
the values that are referenced in the format string.
Str.format()
In this string formatting we use format() function on a string object and braces {} , the
string object in format() function is substituted in place of braces {} . We can use
the format() function to do simple positional formatting, just like % formatting.
Example 6:
name = 'world'
print('Hello, {}'.format(name))
Hello,world
In this example we used braces {} and format() function to pass name object .We got the
value of name in place of braces {} in output.
We can refer to our variable substitutions by name and use them in any order we want.
This is quite a powerful feature as it allows for re-arranging the order of display without
changing the arguments passed to the format function.
Example 7:
name = 'world'
program ='python'
In this example we specified the variable substitutions place using the name of variable
and pass the variable in format() .
2. In str.format() method we pass the string object to the format() function for string
interpolation.