Python Strings
Strings
Single or double quotation marks are used to surround strings in Python.
'hello'
is the same as "hello"
.
Example :- The print()
function allows you to show a literal string :
#You can use double or single quotes:
print("Hello")
print('Hello')
Output :-
Hello
Assign String to a Variable
The variable identity is assigned to a string guided by the same sign and string :
Example :-
a = "Hello"
print(a)
Output :-
Multiline Strings
While using three quotes, you can set a multiline string to a variable :
Example 1 :- You can use three double quotes :
a = """First Line,
Second Line,
Last Line."""
# Or three single quotes
a = '''First Line,
Second Line,
Last Line.'''
print(a)
Output :-
Second Line,
Last Line.
Note : the line cuts are inserted at the same location as the script in the consequence.
Strings are Arrays
Strings are arrays of bytes in Python that represent unicode characters like most other popular programming language.
However, Python has no data type, but only one character is a string with a length of 1.
Brackets can be used for accessing string elements.
Example :- Have the position 1 character (remember that position 0 for the first character) :
a = "Hello, World!"
print(a[1])
Output :-
Looping Through a String
Because strings are arrays, we can use a for
loop to iterate through the characters in a string.
Example :- Loop through the letters in the word "banana" :
for x in "banana":
print(x)
Output :-
a
n
a
n
a
String Length
Example :- Can use len()
function to obtain a string length :
a = "Hello, World!"
print(len(a))
Output :-
Related Links
Check String
We can use the keyword in
to see if a specific phrase or character is present in a string.
Example :- Examine the following text to see if the word "free" appears :
txt = "The best things in life are free!"
print("free" in txt)
Output :-
In an if
statement, you can use it as follows :
Example 2 :- Print only if "free" is present :
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
Output :-
Check if NOT
We can use the keyword not in
determine if a certain sentence or character does NOT appear in a string.
Example 1 :- Examine the following text to see if the word "expensive" is missing :
txt = "The best things in life are free!"
print("expensive" not in txt)
Output :-
Use it in an if
statement :
Example 2 :- print only if "expensive" is NOT present :
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
Output :-
Python Slicing - Extract Substring or Part of String
The slice syntax allows you to return a range of characters.
Specify the start index and end index, separated by a colon(:), to return a section of the string.
Example 1 :- Figure out where each character is located between positions 2 and 5 :
b = "Hello, World!"
print(b[2:5])
Output :-
Note :- The end index will not be included in the output.
Note :- It's important to note that the first character has an index of 0.
Slice From the Start
The range will begin at the first character if the start index is not specified.
Example 2 :- Get the characters from the beginning to position 5 :
b = "Hello, World!"
print(b[:5])
Output :-
Slice To the End
Example 3 :- Leaving out the end index will cause the range to go to the end of the range :
b = "Hello, World!"
print(b[2:])
Output :-
Negative Indexing
Example 4 :- Slices can be started from the end of the string by using negative indexes :-
b = "Hello, World!"
print(b[-5:-2])
Output :-
Python - Modify Strings
Strings can be used with Python's built-in methods.
Python String - Lower Case and Upper Case
The lower()
method is used to convert strings into lower case letter.
The upper()
method is used to convert strings into upper case letter.
Example :-
a = "Hello, World!"
print(a.lower())
print(a.upper())
Output :-
HELLO, WORLD!
Strings are returned in lower case using the function lower()
:
The upper()
method returns a string that is all capital letters :
Related Links
Remove Whitespace
The space before and/or after the actual text is known as whitespace, and it's fairly common to desire to get remove of it.
The strip()
method is used to remove the spaces at beginning and/or end of the string.
A space may be a whitespace, Tab key, or Newline.
Example :- The following example will eliminate any spaces at beginnig or end of the string :
a = " Hello, World! "
print(a.strip())
Output :-
Replace String
The replace()
function is used replace a substring with another substring.
Example :-
a = "Hi Hello!"
print(a.replace("H", "J"))
print(a.replace("Hi", "Say"))
Output :-
Say Hello!
Split String
A string can be splitted into multiple chunks using any separator.
A separator may be any character which is used to split the string into substrings.
With the split()
method, you can create a list in which the text between separators is shown as list items.
Example :- It finds occurrences of the separator, the split()
method breaks the string into substrings :
a = "Hello, World!"
b = a.split(",")
print(b)
m = "123-3736458";
print(m.split("-"))
Output :-
['123', '3736458"
String Concatenation
The +
operator can be used to concatenate or merge two strings.
Example 1 :- Variable a
and variable b
should be combined into variable c
:
a = "Hello"
b = "World"
c = a + b
print(c)
Output :-
Example 2 :- To create a space between them, add a " "
before or after them :
a = "Hello"
b = "World"
c = a + " " + b
print(c)
Output :-
String Format
In python, We cannot combine a string and a number or other types.
Example 1 :- In the Python Variables chapter, we learnt that it is not possible to combine strings and numbers in this manner :
age = 36
txt = "My name is John, I am " + age
print(txt)
Output :-
File "demo_string_format_error.py", line 2, in < module>
txt = "My name is John, I am " + age
TypeError: must be str, not int
The format()
method allows us to combine texts and numbers together.
As a result, format()
accepts a string as a parameter, formats it, and inserts its contents into the string where the placeholders {}
are :
Example 2 :- To put numbers into strings, use the format()
method :
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
Output :-
Example 3 :- Any number of arguments may be passed to the format()
method, and they will be placed in the appropriate placeholders :
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price)
Output :-
Example 4 :- In order to ensure that arguments are placed in the correct placeholders, utilise index numbers {0}
:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Output :-
Escape Character
Use an escape character to insert characters that are illegal in a string.
After a backslash \
, insert the character you want to escape.
A double quotation inside a string enclosed by double quotes is an example of an illegal character :
Example 1 :- Using double quotes within a double quote-enclosed string will result in an error :
txt = "We are the so-called "Vikings" from the north."
#You will get an error if you use double quotes inside a string that are surrounded by double quotes:
Output :-
txt = "We are the so-called "Vikings" from the north."
^
SyntaxError: invalid syntax
Use the escape character \"
to remedy this problem :
Example 2 :- As a result of this escape character, you are able to utilise double quotes in places where you would not ordinarily be allowed :
txt = "We are the so-called \"Vikings\" from the north."
print(txt)
Output :-