Python Tutorials
- Python
- How to install Python?
- PIP
- How to Run Python Program
- Python Identifiers,Statement, Indentation and Comments
- Variable
- Data type
- Decision Making
- Python Loops
- Break,Continue, Pass
- Functions
- Predefine Functions
- Lambda Functions
- Variable Scope
- List
- Tuple
- Python Sets
- Python Dictionary
- Python String
- String Formating
- Input/Output
- File Handling (Input / Output)
- Iterators
- Python Modules
- Python Date
- Python JSON
- Classes and Objects
- Constructor
- Polymorphism
- Encapsulation
- inheritance
- Class or Static Variables in Python
- class method vs static method
- Abstraction
- Exception Handling
- MySql Python
- MySql Create Database
- MySql CRUD
- Django
What is Python String?
A string is a sequence of characters. In Python, a string is a sequence of Unicode characters.
This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and Unicode are some of the popular encodings used.
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes.
How to create a string in Python?
File name : index.py
# defining strings in Python
# all of the following are equivalent
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python"""
print(my_string)
How to access characters in a string?
File name : index.py
We can access individual characters using indexing and a range of characters using slicing. Index starts from 0. Trying to access a character out of index range will raise an IndexError. The index must be an integer. We can't use floats or other types, this will result into TypeError.
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of items in a string by using the slicing operator :(colon).
Example
File name : index.py
#Accessing string characters in Python
str = 'programiz'
print('str = ', str)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
#slicing 2nd to 5th character
print('str[1:5] = ', str[1:5])
#slicing 6th to 2nd last character
print('str[5:-2] = ', str[5:-2])
Output :-
str = programiz
str[0] = p
str[-1] = z
str[1:5] = rogr
str[5:-2] = am
Strings indexing and splitting
File name : index.py
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])
example
File name : index.py
# Given String
str = "itechxpert" javatpoint
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])
Output:
itechxpert
chxp
ec
ite
hxp
How to change or delete a string?
Strings are immutable. This means that elements of a string cannot be changed once they have been assigned. We can simply reassign different strings to the same name.
File name : index.py
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object doesn't support item assignment i.e., A string can only be replaced with new string since its content cannot be partially replaced. Strings are immutable in Python.
File name : index.py
str = "HELLO"
print(str)
str = "hello"
print(str)
Output:
HELLO
hello
Deleting the String
We cannot delete or remove the characters from the string. But we can delete the entire string using the del keyword.
File name : index.py
str1 = "JAVATPOINT"
del str1
print(str1)
Output:
NameError: name 'str1' is not defined
String Operators
File name : index.py
Operator Description
+ It is known as concatenation operator used to join the strings given either side of the operator.
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[] It is known as slice operator. It is used to access the sub-strings of a particular string.
[:] It is known as range slice operator. It is used to access the characters from the specified range.
in It is known as membership operator. It returns if a particular sub-string is present in the specified string.
not in It is also a membership operator and does the exact reverse of in. It returns true if a particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we need to print the actual meaning of escape characters such as "C://python". To define any string as a raw string, the character r or R is followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers used in C programming like %d or %f to map their values in python. We will discuss how formatting is done in python.
The format() method
The format() method is the most flexible and useful method in formatting strings. The curly braces {} are used as the placeholder in the string and replaced by the format() method argument.
File name : index.py
# Using Curly braces
print("{} and {} both are the best friend".format("Devansh","Abhishek"))
#Positional Argument
print("{1} and {0} best players ".format("Virat","Rohit"))
#Keyword Argument
print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))
Output:
Devansh and Abhishek both are the best friend
Rohit and Virat best players
James,Peter,Ricky
Python String functions :-
File name : index.py
Python String Operations
Concatenation of Two or More Strings
Joining of two or more strings into a single one is called concatenation.
The + operator does this in Python. Simply writing two string literals together also concatenates them.
The * operator can be used to repeat the string for a given number of times.
File name : index.py
# Python String Operations
str1 = 'Hello'
str2 ='World!'
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
Iterating Through a string
We can iterate through a string using a for loop.
File name : index.py
# Iterating through a string
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')
Output :-
3 letters found
String Membership Test
We can test if a substring exists within a string or not, using the keyword in.
File name : index.py
>>> 'a' in 'program'
True
>>> 'at' not in 'battle'
False
String Methods
File name : index.py
Python includes the following built-in methods to manipulate strings −
Sr.No. Methods with Description
1 capitalize()
Capitalizes first letter of string
2 center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width columns.
3 count(str, beg= 0,end=len(string))
Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.
4 decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.
5 encode(encoding='UTF-8',errors='strict')
Returns 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))
Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.
7 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.
8 find(str, beg=0 end=len(string))
Determine if str occurs in string or in 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()
Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
11 isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
12 isdigit()
Returns true if string contains only digits and false otherwise.
13 islower()
Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
14 isnumeric()
Returns true if a unicode string contains only numeric characters and false otherwise.
15 isspace()
Returns true if string contains only whitespace characters and false otherwise.
16 istitle()
Returns true if string is properly "titlecased" and false otherwise.
17 isupper()
Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
18 join(seq)
Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.
19 len(string)
Returns the length of the string
20 ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to a total of width columns.
21 lower()
Converts all uppercase letters in string to lowercase.
22 lstrip()
Removes all leading whitespace in string.
23 maketrans()
Returns a translation table to be used in translate function.
24 max(str)
Returns the max alphabetical character from the string str.
25 min(str)
Returns the min alphabetical character from the string str.
26 replace(old, new [, max])
Replaces all occurrences of old in string with new or at most max occurrences if max given.
27 rfind(str, beg=0,end=len(string))
Same as find(), but search backwards in string.
28 rindex( str, beg=0, end=len(string))
Same as index(), but search backwards in string.
29 rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to a total of width columns.
30 rstrip()
Removes all trailing whitespace of string.
31 split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.
32 splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.
33 startswith(str, beg=0,end=len(string))
Determines if 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])
Performs both lstrip() and rstrip() on string.
35 swapcase()
Inverts case for all letters in string.
36 title()
Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.
37 translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing those in the del string.
38 upper()
Converts lowercase letters in string to uppercase.
39 zfill (width)
Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).
40 isdecimal()
Returns true if a unicode string contains only decimal characters and false otherwise.