String
Strings are arrays of bytes representing Unicode characters. String is a collection of one or more characters put in a single quote, double-quote or triple quote. In Python there is no character data type, a character is a string of length one. It is represented by the `str` class.
Example:
# Creating string with single quotes
String1 = 'Welcome to the Libed'
print('String with the use of Single Quotes:', String1)
# Creating string with triple quotes allows multiple lines
String1 = '''Libed
Python
Tutorial'''
print('''Creating a multiline String:''', String1)
Output:
String with the use of Single Quotes: Welcome to the Libed
Creating a multiline String: Libed
Python
Tutorial
Accessing characters: Individual characters of a string can be accessed by using the method of indexing. Indexing allows negative addresses to access characters from the back of the string.
| L | I | B | E | D |
|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 |
| -5 | -4 | -3 | -2 | -1 |
Example:
# Access characters of String
String1 = "LIBED"
print("Initial String:", String1)
# Printing First character
print("First character of String is:", String1[0])
# Printing Last character
print("Last character of String is:", String1[-1])
Output:
Initial String: LIBED
First character of String is: L
Last character of String is: D
String Slicing: To access a range of characters in the string, the method of slicing is used. Slicing is done by using a slicing operator (colon).
Example:
# String slicing
String1 = "Libed Tutorials"
print("Initial String:", String1)
# Printing 3rd to 5th character
print("Slicing characters from 3-6:", String1[3:6])
# Printing characters between 3rd and 2nd last character
print("Slicing characters between " + "3rd and 2nd last character:", String1[3:-1])
Output:
Initial String: Libed Tutorials
Slicing characters from 3-6: ed
Slicing characters between 3rd and 2nd last character: ed Tutorial
Deleting/Updating from a String: Updation or deletion of characters from a string is not allowed. This will cause an error because item assignment or item deletion from a string is not supported. Although deletion of the entire string is possible with the use of a built-in del keyword. This is because strings are immutable, hence elements of a string cannot be changed once it has been assigned. Only new strings can be reassigned to the same name.
Example:
# Update entire String
String1 = "Libed"
print("Initial String: ", String1)
# Updating a String
String1 = "Python Tutorial"
print("Updated String: ", String1)
# Deleting a String with the use of del
String2 = "Python Tutorial"
del String2
print("Deleting entire String:", String2)
Output:
Initial String: Libed
Updated String: Python Tutorial
NameError: name 'String2' is not defined
Formatting of Strings: Strings in Python can be formatted with the use of format() method which is a very versatile and powerful tool for formatting strings. Format method in string contains curly braces {} as placeholders which can hold arguments according to position or keyword to specify the order.
Example:
# Formatting of Strings
# Default order
String1 = "{} {} {}".format('Libed', 'Python', 'Tutorial')
print("Print String in default order:", String1)
# Positional Formatting
String1 = "{1} {0} {2}".format('Tutorial', 'Python', 'Libed')
print("Print String in Positional order:", String1)
# Keyword Formatting
String1 = "{p} {t} {l}".format(l='Libed', p='Python', t='Tutorial')
print("Print String in order of Keywords:", String1)
Output:
Print String in default order: Libed Python Tutorial
Print String in Positional order: Python Tutorial Libed
Print String in order of Keywords: Python Tutorial Libed
String Methods
Python string is a sequence of Unicode characters that is enclosed in the quotation marks. The in-built functions are the functions provided by Python to operate on strings. Every string method does not change the original string, instead returns a new string with the changed attributes.
Below are few common string methods:
capitalize()
Python string capitalize() method returns a copy of the original string and converts the first character of the string to a capital (uppercase) letter, while making all other characters in the string lowercase letters.
Syntax is string_name.capitalize().
The capitalize() function does not take any parameter.
Example:
str1 = "hello world"
print(str1.capitalize())
Output:
Hello world
count()
Python string count() function is an inbuilt function that returns an integer that denotes the number of times a substring occurs in a given string.
Syntax is string.count(substring, start=..., end=...).
The count() function has one compulsory and two optional parameters. They are:
substring— string whose count is to be found.start(optional) — starting index within the string where the search starts.end(optional) — ending index within the string where the search ends.
Example:
str1 = 'my favorite subject is python, python is a programming language'
print(str1.count('is'))
print(str1.count('is', 10, 40))
Output:
2
1
endswith()
Python string endswith() method returns True if a string ends with the given suffix, otherwise returns False.
Syntax is str.endswith(suffix, start, end).
The parameters are:
suffix— nothing but a string that needs to be checked.start(optional) — It is the starting position from where the suffix is needed to be checked within the string.end(optional) — It is the ending position + 1 from where the suffix is needed to be checked within the string.
Returns True if the string ends with the given suffix otherwise return False.
Example:
txt = "Hello, welcome to my world."
x = txt.endswith("my world.")
print(x)
x = txt.endswith("my world.", 5, 11)
print(x)
Output:
True
False
lower()
Python string islower() method checks and returns True if all characters in the string are lowercase otherwise returns False.
Syntax is string.islower().
Example:
txt = "hello world!"
x = txt.islower()
print(x)
a = "Hello world!"
b = "hello 123"
c = "LIBED"
print(a.islower())
print(b.islower())
print(c.islower())
Output:
True
False
True
False
join()
join() method returns a string concatenated with the elements of iterable. It is an inbuilt string function used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string.
Syntax is string_name.join(iterable).
Iterable parameters are objects capable of returning their members one at a time. Some examples are List, Tuple, String, Dictionary, and Set.
Example:
myTuple = ("John", "Peter", "Vicky")
x = "#".join(myTuple)
print(x)
myDict = {"name": "John", "country": "Norway"}
mySeparator = "TEST"
x = mySeparator.join(myDict)
print(x)
Output:
John#Peter#Vicky
nameTESTcountry