The perfect place for easy learning...

Python

×

Topics List


Python Strings





A string is a sequence of characters which is enclosed in quotes. In Python, a string value can be enclosed either in single quotes or double quotes. The Python treats both single quote and double quote as same. For example, the strings 'Hi Friend' and "Hi Friend" both are same.

Creating Strings

In Python, creating string variables is very simple as we need to assign a string value to a variable.

Example - Creating Strings


wish_1 = 'Good Morning'
wish_2 = "Good Evening"
print(f"wish_1 data type is {type(wish_1)} and wish_2 data type is {type(wish_2)}")

Accessing String Values

In Python, whenever a string data value has assigned to a variable, it is organized as an array of characters. The Python provides a variety of ways to access the string values. Let's consider the following string value.

Python Strings

☀ Accessing whole string

To access the entire string which is stored in a variable, we use the variable name directly. Let's look at the code of how a string value is accessed.

Example - Accessing whole String


wish = 'Good Morning'
print(wish)

When we run the above code, it produces the output as follows.

Python Strings

☀ Accessing a character from a String Values

To access a single character from a string variable, we use the index value in square brackets os the respective character. Let's look at the code of how a character can be accessed from a string value.

Example - Accessing a single character from a Strings


wish = 'Good Morning'
print(wish[0])

When we run the above code, it produces the output as follows.

Python Strings

We can also access a single character from a string using negative index values. When we use negative index value, it starts from the last character with index -1. Let's look at the following example code to demonstrate how negative index values are used to access individual character from a string.

Example - Accessing a single character using the negative index value from a Strings


wish = 'Good Morning'
print(wish[-2])

When we run the above code, it produces the output as follows.

Python Strings

☀ Accessing a Substring from a String Values

In Python, it also possible to access a substring from a string. To access substring from a string, we use string variable name followed by square brackets with starting index and ending index of the required substring. Let's look at the following example code to demonstrate how to access substring from a string.

Example - Accessing a substring from a Strings


wish = 'Good Morning'
print(wish[2:8]) # Accessing specified substring
print(wish[:8]) # Here default starting index is '0'
print(wish[2:]) # Here default Ending index is 'Last - (11)'

When we run the above code, it produces the output as follows.

Python Strings

Special Operators with Strings

The Python programming language provides special operators which can be used with string data values. The following table gives the list of special operators used with strings.

S.No. Operator Description
1 + It is used to perform concatenation - Adds values on either side of the operator.
2 * It is used to Reproduction - Generates new strings, concatenating multiple copies of the same string.
3 in It is used to check whether a character is present in the string.
3 not in It is used to check whether a character is not present in the string.
3 r/R It is used to print raw data in a string
3 [ ] It is used to access a character at a specified index.
3 [ : ] It is used to access a substring from a string.

Example - Special Operators used with strings


wish_1 = "Hi"
wish_2 = 'Good Morning'
result = wish_1 + wish_2
print(result)
result = 3 * wish_2
print(result)

When we run the above code, it produces the output as follows.

Python Strings

Built-in functions to handle strings

The Python programming language provides a built-in class called str which provides a wide range of built-in function to handle string data values.

S.No. Function Description
1 capitalize() It is used to Capitalizes the first letter of a string
2 center(width, fill_char) It is used to Returns a space-padded string with the original string centered to a total of width columns.
3 count(str, beg= 0,end=len(string)) It is used to Count how many times str occurs in string or a substring of string if starting index beg and ending index end are given.
4 decode(encoding='UTF-8',errors='strict') It is used to Decode the string using the codec registered for encoding. encoding defaults to the default string encoding.
5 encode(encoding='UTF-8',errors='strict') It is used to Return encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'.
6 endswith(suffix, beg=0, end=len(string)) It is used to determine if a string or a substring of string (if starting index beg and ending index end are given) ends with a suffix; returns true if so and false otherwise.
7 expandtabs(tab_size=8) It is used to expand tabs in a string to multiple spaces; defaults to 8 spaces per tab if tab_size not provided.
8 find(str, beg=0 end=len(string)) It is used to determine if str occurs in a string or a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.
9 index(str, beg=0, end=len(string)) Same as find(), but raises an exception if str not found.
10 isalnum() It is used to return true if a string has at least 1 character and all characters are alphanumeric and false otherwise.
11 isalpha() It is used to return true if a string has at least 1 character and all characters are alphabetic and false otherwise.
12 isdigit() It is used to return true if a string contains only digits and false otherwise.
13 islower() It is used to return true if a string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
14 isnumeric() It is used to return true if a Unicode string contains only numeric characters and false otherwise.
15 isspace() It is used to Return true if the string contains only whitespace characters and false otherwise.
16 istitle() It is used to Return true if string is properly "titlecased" and false otherwise.
17 isupper() It is used to Return true if a string has at least one cased character and all cased characters are in uppercase and false otherwise.
18 join(seq) It is used to merge (concatenate) the string representations of elements in sequence seq into a string, with separator string.
19 ljust(width[, fillchar]) It is used to return a space-padded a string with the original string left-justified to a total of width columns.
20 lower() It is used to convert all uppercase letters in a string to lowercase.
21 lstrip() It is used to remove all leading whitespace in a string.
22 maketrans() It is used to return a translation table to be used in translate function.
23 max(str) It is used to return the max alphabetical character from the string str.
24 min(str) It is used to return the min alphabetical character from the string str.
25 replace(old, new [, max]) It is used to replace all occurrences of old in the string with new or at most max occurrences if max given.
26 rfind(str, beg=0,end=len(string)) Same as find(), but search backwards in a string.
27 rindex( str, beg=0, end=len(string)) Same as index(), but search backwards in a string.
28 rjust(width,[, fillchar]) It is used to return a space-padded a string with the original string right-justified to a total of width columns.
29 rstrip() It is used to remove all trailing whitespace of a string.
30 split(str="", num=string.count(str)) It is used to Split string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.
31 splitlines( num=string.count('\n')) It is used to split a string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.
32 startswith(str, beg=0,end=len(string)) It is used to determine if a string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.
33 startswith(str, beg=0,end=len(string)) It is used to determine if a string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.
34 strip([chars]) It is used to perform both lstrip() and rstrip() on a string.
35 swapcase() It is used to invert case for all letters in a string.
36 title() It is used to return "titlecased" version of a string, that is, all words begin with uppercase and the rest are lowercase.
37 translate(table, deletechars="") It is used to translate a string according to translation table str(256 chars), removing those in the del string.
38 upper() It is used to convert lowercase letters in a string to uppercase.
39 zfill (width) It is used to return original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).
40 isdecimal() It is used to return true if a Unicode string contains only decimal characters and false otherwise.