How Can We Help?
In this tutorial, we are going to explain how to use Python String with basic syntax and many examples for better understanding. but let’s see first the definition of string in python down below :
What is String in Python? Python String is a sequence of Unicode characters or a bunch of words represented in quotation marks. It stores and represents text-based information like “Welcome python”.
(See the official python.org strings docs.)
String includes characters(A-Z, a-z), numbers(0-9) and special characters(@,!,#,$,%,^,&,*,(,),?,/ etc.)
Syntax:
<string_variable_name>=<string value in quotes>
Example (1) :
Eg 1. Var_1=‘python’,Var_2=“Hello World”
Python accepts single (‘), double (“) and triple (”’ or “””) quotes to indicate the string and always uses the same type of quotes to start and end the string. Python treats all quotes statements the same.
Quote | Example |
Single | ‘Python is an easy language.’ |
Double | “Welcome Python Tool, Let’s learn Python” |
Triple | ”’ Hi John, ‘How are you?’, “Are you there? ” , I am waiting for your reply. ”’ |
Note: Triple quotes are used to create a multiline string and docstrings.
Empty String :
The empty string is written as two quotes with space, i.e. containing nothing.
Example (2) :
str1=' ', mystr=' '
In the above Example, ‘str1’ and ‘mystr’ are string variable name and two quotes (‘ ‘) shows empty string values.
Multiple String Assignment:
We can assign multiple strings with their values in a single line by multiple string assignment.
Example (3) :
# multiple string assignment
number, alphabet= '123' , 'abc'
print('number:',number)
print('alphabet:',alphabet)
Example (3) Output:
number: 123
alphabet: abc
In the above Example, number and alphabet is the list variable name, and ‘123’ and ‘abc’ are respective values.
Accessing String Values:
In Python, Strings are stored as individual characters in a nearby memory location. We can access the individual characters in a string through indexing from both the directions (i.e. forward and backward) and the index value of the element is given in the square brackets like [0],[1].
According to the above image, the forward indexing starts from the left to right like 0,1,2,…..,n, and the last character index position is n-1. Forward indexing is also known as positive indexing.
The backward indexing starts from the left to right like -1,-2,-3,…..,-n, and the last character index position is -n. Backward indexing is also known as negative indexing.
Syntax:
<string variable name>[<expression/index_val>]
Here, the value of <expression> determines which character is selected from the string.
Example (4) :
#Accessing string index
myStr=“myPYTHON”
print(myStr[0]) # accessing 0 or -8 index
print(myStr[-2]) # accessing -2 or 7 index
Example (4) Output:
‘m’
‘O’
In the above example, for string variable ‘myStr’, we are accessing the 0th or -8th position of string by the positive index [0] or negative index [-8] respectively as myStr[0] or myStr[-8]. Therefore, in print statement output is ‘m’ which is at 0th or -8th position of the string. The other line of code also works like the same only we have taken a negative index.
String index out of range index error
If we try to access the index of string that exceeds the range of string, then the program code will raise an IndexError exception.
Example (5) :
#Accessing out of range index
myString="Welcome Java"
print(myString[12])
Example (5) Output:
Traceback (most recent call last):
File “”, line 1, in
myString[12]
IndexError: string index out of range
In the above Example, ‘ myString ‘ is a string variable name and its value has an index up to 11 but here, we are accessing the 12th index value by myString[12] in the print statement, which is not a part of the string, so we got an IndexError as ‘string index out of range’ in output.
Incorrect Type of String Index
While we are using the float or other data types as an index of string then it will throw a TypeError. The index value accepts only integer values.
Example (6) :
#Accessing incorrect type of index
myString=”Hello Python”
print(myString[1.5])
Example (6) Output:
Traceback (most recent call last) :
Fille “”, line 1, in
print (myString [1.5])
TypeError : string indices must be integers
In the above Example, ‘ myString ‘ is a string variable name and it has a forward index value of 0 to 11 but here, we are accessing the 1.5th index value by myString[1.5] in the print statement, which is a float value and string supports only integer index so we got a TypeError as ‘string indices must be integers’ in output.
String as Immutable
A string is an immutable means elements of a string can’t be changed once it has been assigned. We can simply reassign different strings to the same name like str1=’python’ and reassignment of str1 is as str1=’Java’.
Example (7) :
name='Oraask'
#Assign value to zero index
name[0]='myO'
Example (7) Output:
Traceback (most recent call last):
File “”, line 1, in
name[0]=’myO’
TypeError: ‘str’ object does not support item assignment
In the above example, we have tried to assign the value as ‘myO’ at zero position but the string is immutable so the program throws a TypeError.
Python string slicing and substring
Substring is the part of the string. We can access a contiguous sequence of the characters from the string is called a substring and the process used for substring is called slicing. We can access a range of characters using slicing operator(colon).
We can slice a string from both directions as for left and right. The slicing syntax considers the start position as the beginning position of the new string and the end position-1 as the last position of the new string. Slicing does not consider the position after the colon means-end position of the syntax.
Syntax:
<variable name>[start position : end position]
OR
<variable name>[start position:]
OR
<variable name>[:end position]
OR
<variable name>[:]
Note: The start and end positions should be integer values only.
In the above image, the string variable is myStr and the string value is “Hello Java”. Let’s see how we get the bunch of characters by using slicing.
Example (8) :
myStr="Hello Java"
#Accessing slicing index of string
print(myStr[:])
print(myStr[-9:-2])
print(myStr[1:6])
print(myStr[-6:])
print(myStr[:3])
Example (8) Output:
‘Hello Java’
‘ello Ja’
‘ello ‘
‘o Java’
‘Hel’
In the above example, we have used the different syntax of slicing to get different results.
We have used myStr[:], which shows whole string value because when start and the end position is not given in the syntax, the output consider start position as (zero) and end position as (last element position of string + 1) so the output shows whole string as ‘Hello Java’.
We have used myStr[-9:-2], which shows a negative index value from -9 to -3 because as per the rule, the end position is not considered in the slicing so the output shows the value of index -9 to -3 i.e. ‘ello ja’.
Same like above, we have used myStr[1:6], which shows a positive index value from 1 to 5 because as per the rule, end position is not considered in the slicing so the output shows the value of index 1 to 5 i.e. ‘ello ‘
We have used myStr[-6:], which shows index value from -6 to -1 because the start position of syntax is -6 and the end position is not given in the syntax but if we use a negative index without end position, then the index of the last element of the string considers as an index of the last element of the output string i.e. -1 so the range of index in output is -6 to -1, which gives a value as ‘o Java’.
We have used myStr[:3], which shows index value from 0 to 2 because the start position is not given in the syntax and we can’t consider start position below zero, so the output considers the start position as 0 indexes of the string and end position is already given so the last element of the result end position-1 index value i.e. 2 so the output of myStr[:3] is ‘Hel’.
Python String Built-In Functions:
Python has following built-in string functions.
Sr. | Function | Description |
---|---|---|
1 | min(string) | It returns a minimum value of a string. |
2 | max(string) | It returns a maximum value of a string. |
3 | len(string) | It returns the total length of a string, which is equal to the number of elements in the string. |
4 | type(string) | It returns the type of string if the passed variable is a string. |
5 | str(seq) | It converts a sequence/string into a string. |
6 | del(string) | It deletes the whole string. |
Python String Basic operations :
We can do the following basic operations on String in Python.
Sr. | Operation | Description |
---|---|---|
1 | Concatenation(‘+’) | It adds two strings together. |
2 | Repetition(‘*’) | It repeats the element of the string. |
3 | Membership(‘in’ & ‘not in’) | It returns True if the given element is present in the string otherwise returns False. |
4 | String Iteration | It returns elements of string by using for loop with string. |
Python String Formatting Methods
Python supports the following string formatting methods, which are used to format the string values.
Sr. | Operation | Description |
---|---|---|
1 | title() | It returns the “titlecased” version of the string means all the words start with uppercase and the remaining are lowercase. |
2 | capitalize() | It capitalizes on the first character of the String. |
3 | center() | It returns a space-padded string with the original string centered to a total of width columns. |
4 | swapcase() | It inverts the case of all the characters in a string. |
5 | lower() | It converts all the characters of a string to lowercase. |
6 | upper() | It converts all the characters of a string to uppercase. |
7 | rstrip() | It removes the particular character of a string from the right side. |
8 | lstrip() | It removes the particular character of a string from the left side. |
9 | strip(chars) | It removes particular characters of a string from the left and right sides. |
10 | ljust() | It returns an original string with a filled specific character or space at the left side of the string value to justify the new length (width) of the string. |
11 | rjust() | It returns an original string with a filled specific character or space at the right side of the string value to justify the new length (width) of the string. |
12 | zfill() | It returns an original string value with filled zero at the left side of the string value to justify the new length (width) of the string. |
In python, we can format the string in two ways.
- Using % operator:
It is the same as other languages such as C, C++, etc. Python supports the following % operators.
Sr. | Format Syntax | Description |
---|---|---|
1 | %s | Used for string data type |
2 | %d | Used for signed decimal integer data type |
3 | %u | Used for unsigned decimal integer data type |
4 | %o | Used for octal integer data type |
5 | %x or %X | Used for hexadecimal integer data type |
6 | %e or %E | Used for exponential notation data type |
7 | %f | Used for floating-point real number data type |
Example (9) :
print('%s earn %d USD per %s' %('John',5000,'month.'))
Example (9) Output:
John earn 5000 USD per month.
In the above example, we have used %s for string and %d for the numeric value and replaced it with ‘John’, 5000 and ‘month.’ by using syntax as ”%s earn %d USD per %s’ %(‘John’,5000,’month.’)’.
Example (10) :
Float_val=1.5689965
print("Round off 1.5689965 is %.2f" % Float_val)
print("Round off 1.5689965 is %.4f" % Float_val)
Example (10) Output:
Round off 1.5689965 is 1.57
Round off 1.5689965 is 1.5690
In the above example, we have used format specifiers ‘.2f’ and ‘.4f’ to round the value of float variable ‘ Float_val’ in the print statements. A ‘.2f’ denotes that we need 2 decimal numbers after the decimal point, so the result is 1.57, and ‘.4f’ denotes that we need 4 decimal numbers after decimal points, so the result is 1.5690.
- Using format() Method :
In python, a format() method is used to format string values and use curly brackets({}) as a placeholder, which will be replaced according to the given arguments or positional arguments, or keyword arguments to specify an order.
Example (11) :
#Using default order
print('Use default order: ')
print('{} earn {} USD per {}'.format('Rimi',2000,'month.'))
print('\n')
#Using positional order
print('Use Positional Argument: ')
print('{0} earn {1} USD per {2}'.format('John',5000,'month.'))
print('{0} earn {1} USD per {2}'.format('Sam',3000,'month.'))
print('\n')
#Using keyword order
print('Use Keyword Argument: ')
print('{name} earn {amount} USD'.format(name='Saini',amount=7000))
print('{name} earn {amount} USD'.format(amount=1000,name='Rick' ))
Example (11) Output:
Use default order:
Rimi earn 2000 USD per month.
Use Positional Argument:
John earn 5000 USD per month.
Sam earn 3000 USD per month.
Use Keyword Argument:
Saini earn 7000 USD
Rick earn 1000 USD
In the above example, we have used curly brackets({}) as a placeholder for 3 types of arguments. In the first print statement, we replace the {} brackets with values according to the order of {} brackets and order of arguments.
In the second print statement, we replaced {} brackets with values according to its position as 0,1 and 2 and position of arguments.
In the third print statement, we replace the {} brackets with values according to used keywords in {} brackets and used keywords for arguments.
We can round the integers (like binary, hexadecimal, etc.) and float in the exponent form with the use of format specifiers, which separated from field name using a colon (:) and justified the string as left-justify (<) or right-justify(>) or center (^) with the use of format specifiers separated by a colon(:).
Example (12) :
#integer formating
print('Integer formatting:')
print('Binary conversation of {0}and {1} is {0:b} and {1:b} respectively'.format(14,16))
print('\n')
#float formating
print('Float formatting:')
print('Exponent conversation of {0} is {0:e}'.format(253.2))
print('\n')
#Round of the float value
print('2/3 is' ,2/3)
#print(Round off float value:')
print('After round off, 2/3 is {0:.2f}'.format(2/3))
print('\n')
#string justification
print('String left, right and center justifiction:')
print('!!{0:<10}!!\n !!{1:>7}!!\n !!{2:^12}!!'.format('python','Java','Ruby'))
print('\n')
Example (12) Output:
Integer formatting:
Binary conversation of 14and 16 is 1110 and 10000 respectively
Float formatting:
Exponent conversation of 253.2 is 2.532000e+02
2/3 is 0.6666666666666666
After round off, 2/3 is 0.67
String left, right and center justifiction:
!!python !!
!! Java!!
!! Ruby !!
In the above example, in the first print statement, we have converted decimal value 14 into binary by using {0:b} where 0 indicates the order of attribute 14 and ‘b’ means to convert a value in binary. The same is for attribute 16; the only order of it is 1.
In the second print statement, {0:e} converts ‘0’ order value 253.2 in exponent format by using {0:e}.
In the third print statement,2/3 is 0.6666666666666666 and {0:.2f} converts ‘0’ order value 0.6666666666666666 in the round off format as 2 decimal numbers after decimal points, so the output shows as 0.67.
In the fourth print statement, we justify the 3 attributes(i.e., Python, Java, and Ruby) as left, right, and center, respectively, against its position as 0,1, and 2. Here 10,7 and 12 are the total lengths of the resulted string.
The resulting string hold attribute against the justification apply on it like left justify apply on the ‘python’ attribute, so the result is ‘python ‘. The string justification is worked the same like ljust() and rjust() methods.
Python String Validation Methods
Python supports the following string validation methods, which are used to check the string values and string formats.
Sr. | Operation | Description |
---|---|---|
1 | isalnum() | It returns True if all the characters of the string are alphanumeric; otherwise, it returns False. |
2 | isdigit() | It returns True if all the characters of the string are digit; otherwise, it returns False. |
3 | isnumeric() | It returns True if all the characters of the string are numeric; otherwise, it returns False. |
4 | isdecimal() | It returns True if all the characters of the string are decimal; otherwise, it returns False. |
5 | isalpha() | It returns True if all the string characters are the alphabet; otherwise, it returns False. |
6 | islower() | It returns True if all the string characters are in lowercase; otherwise, it returns False. |
7 | isupper() | It returns False if all the string characters are in an uppercase; otherwise, it returns False. |
8 | isspace() | It returns True if all the characters of a string are whitespace; otherwise, it returns False. |
9 | istitle() | It returns True if all the string words are properly “title cased”; otherwise, it returns False. |
10 | startswith() | It returns True if the string starts with a given substring between the given start and end index; otherwise, it returns False. |
11 | endswith() | It returns True if the string ends with a given substring between start and end index; otherwise, it returns False. |
Python String Manipulation Methods
Python supports the following string manipulation methods, which are used to perform functionality operations on strings.
Sr. | Operation | Description |
---|---|---|
1 | count() | It counts how many a number of times a given substring occurs in a string between the given start and end index. |
2 | join() | It merges (concatenates) the sequence into a string. |
3 | replace() | It replaces the old string value with a new string value. |
4 | split() | It splits the string according to the passed delimiter string and returns the list of substrings. |
5 | splitlines() | It splits the string at all newlines or the number of newlines and returns a list of each line with newlines removed. |
6 | find() | It returns the index value of the string, where a given substring is found between the given start index and end index. |
7 | rfind() | It works the same as the find() method but only searches from the backward in a string. |
8 | index() | It works same like find() method only raises an exception if a substring is not found in a string between the given start and end index |
9 | rindex() | It works the same as the index() method but only searches from the backward in a string. |
Python String Escape Characters
Python supports the following escape characters, which are represented with backslash notation. It used to format the string value like differentiate single line string into two lines by using a backslash before ‘n’, adding a tab in string line by using a backslash before ‘t’, creating different symbols by using a backslash before some alphabets, etc.
Escape Ch | Description | Input | Output |
---|---|---|---|
\n | It returns a single-line string in two separate lines. We also call it a newline. | print(‘python\nJava’) | python java |
\a | It returns the symbol of a bell or ASCII bell. | print(‘\a’) | try to see the output |
\b | It returns the symbol of a dot inbox or ASCII backspace. | print(‘\b’) | try to see the output |
\f | It returns the symbol of square or ASCII formfeed. | print(‘\f’) | try to see the output |
\t | It creates a horizontal tab in string. | print(‘python\tlanguage’) | python language |
\v | It creates a vertical tab in string. | print(‘python\vlanguage’) | Python language |
\oOct or \oOctOct | It returns the character with an octal value. | print(‘Octal Symbol: \052\025\065’) | Octal Symbol: *5 |
\xHex or \xHexHex | It returns a character with a hexadecimal value. | print(‘A \x48\x45\x58 representation’) | A HEX representation |
In the above examples, we have used print statements and get the result according to the name of the escape character.
Python Raw String
To ignore the escape characters inside a string, we use ‘r’ or ‘R’ in front of the string value. It means it is a raw string and would ignore any escape sequence inside it. It is mainly used when we use the path address of any file.
Example (13) Without Raw String :
print('This is \x50 \nexample.')
Example (13) Output:
This is P
example.
In the above example, we can see that all the escape characters like newline and hex number are included.
Example (14) With Raw String :
print(r'This is \x50 \nexample.')
Example (14) Output:
This is \x50 \nexample.
In the above example, after using the raw string ‘r’, these escape characters are ignored, so output prints these escape characters as a string value.
In this tutorial, you have learned how to use python String.
If you have an inquiry or doubt don’t hesitate to leave them in the comment section. we are waiting for your feedback.But remember to understand the concept very well, you need to practice more.
Hopefully, it was clear and concise.
Python Tutorials List:
- Python tutorials list : access all python tutorials.