Python program to find number of vowels in a given string.
mystr ="All animals are equal. Some are more equal"
vowels ="aeiou"
count=0for x in mystr:if x.lower()in vowels: count+=1print("Number of Vowels:", count)
It will produce the following output −
Number of Vowels: 18
Example 2
Python program to convert a string with binary digits to integer.
mystr ='10101'defstrtoint(mystr):for x in mystr:if x notin'01':return"Error. String with non-binary characters"
num =int(mystr,2)return num
print("binary:{} integer: {}".format(mystr,strtoint(mystr)))
It will produce the following output −
binary:10101 integer: 21
Change mystr to ’10, 101′
binary:10,101 integer: Error. String with non-binary characters
Example 3
Python program to drop all digits from a string.
digits =[str(x)for x inrange(10)]
mystr ='He12llo, Py00th55on!'
chars =[]for x in mystr:if x notin digits:
chars.append(x)
newstr =''.join(chars)print(newstr)
It will produce the following output −
Hello, Python!
Exercise Programs
Python program to sort the characters in a string
Python program to remove duplicate characters from a string
Python program to list unique characters with their count in a string
Python program to find number of words in a string
Python program to remove all non-alphabetic characters from a string
Python’s built-in str class defines different methods. They help in manipulating strings. Since string is an immutable object, these methods return a copy of the original string, performing the respective processing on it. The string methods can be classified in following categories −
Case Conversion Methods
This category of built-in methods of Python’s str class deal with the conversion of alphabet characters in the string object. Following methods fall in this category −
title()Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase.
6
upper()Converts lowercase letters in string to uppercase.
Alignment Methods
Following methods in the str class control the alignment of characters within the string object.
Sr.No.
Methods & Description
1
center(width, fillchar)Returns a string padded with fillchar with the original string centered to a total of width columns.
2
ljust(width[, fillchar])Returns a space-padded string with the original string left-justified to a total of width columns.
3
rjust(width,[, fillchar])Returns a space-padded string with the original string right-justified to a total of width columns.
4
expandtabs(tabsize = 8)Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.
5
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).
Split and Join Methods
Python has the following methods to perform split and join operations −
rstrip()Removes all trailing whitespace of string.
3
strip()Performs both lstrip() and rstrip() on string
4
rsplit()Splits the string from the end and returns a list of substrings
5
split()Splits string according to delimiter (space if not provided) and returns list of substrings.
6
splitlines()Splits string at NEWLINEs and returns a list of each line with NEWLINEs removed.
7
partition()Splits the string in three string tuple at the first occurrence of separator
8
rpartition()Splits the string in three string tuple at the ladt occurrence of separator
9
join()Concatenates the string representations of elements in sequence into a string, with separator string.
10
removeprefix()Returns a string after removing the prefix string
11
removesuffix()Returns a string after removing the suffix string
Boolean String Methods
Following methods in str class return True or False.
Sr.No.
Methods & Description
1
isalnum()Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
2
isalpha()Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
3
isdigit()Returns true if the string contains only digits and false otherwise.
4
islower()Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
5
isnumeric()Returns true if a unicode string contains only numeric characters and false otherwise.
6
isspace()Returns true if string contains only whitespace characters and false otherwise.
7
istitle()Returns true if string is properly “titlecased” and false otherwise.
8
isupper()Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
9
isascii()Returns True is all the characters in the string are from the ASCII character set
10
isdecimal()Checks if all the characters are decimal characters
11
isidentifier()Checks whether the string is a valid Python identifier
12
isprintable()Checks whether all the characters in the string are printable
Find and Replace Methods
Following are the Find and Replace methods in Python −
Sr.No.
Method & Description
1
count(sub, beg ,end)Counts how many times sub occurs in string or in a substring of string if starting index beg and ending index end are given.
2
find(sub, beg, end)Determine if sub 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.
startswith(sub, beg, end)Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring sub; returns true if so and false otherwise.
8
endswith(suffix, beg, end)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.
Translation Methods
Following are the Translation methods of the string −
Sr.No.
Method & Description
1
maketrans()Returns a translation table to be used in translate function.
2
translate(table, deletechars=””)Translates string according to translation table str(256 chars), removing those in the del string.
An escape character is a character followed by a backslash (\). It tells the Interpreter that this escape character (sequence) has a special meaning. For instance, \n is an escape sequence that represents a newline. When Python encounters this sequence in a string, it understands that it needs to start a new line.
Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according to rules similar to those used by Standard C. In Python, a string becomes a raw string if it is prefixed with “r” or “R” before the quotation symbols. Hence ‘Hello’ is a normal string whereas r’Hello’ is a raw string.
Example
In the below example, we are practically demonstrating raw and normal string.
# normal string
normal ="Hello"print(normal)# raw string
raw =r"Hello"print(raw)
Output of the above code is shown below −
Hello
Hello
In normal circumstances, there is no difference between the two. However, when the escape character is embedded in the string, the normal string actually interprets the escape sequence, whereas the raw string doesn’t process the escape character.
Example
In the following example, when a normal string is printed the escape character ‘\n’ is processed to introduce a newline. However, because of the raw string operator ‘r’ the effect of escape character is not translated as per its meaning.
normal ="Hello\nWorld"print(normal)
raw =r"Hello\nWorld"print(raw)
On running the above code, it will print the following result −
Hello
World
Hello\nWorld
Escape Characters in Python
The following table shows the different escape characters used in Python –
Sr.No
Escape Sequence & Meaning
1
\<newline>Backslash and newline ignored
2
\\Backslash (\)
3
\’Single quote (‘)
4
\”Double quote (“)
5
\aASCII Bell (BEL)
6
\bASCII Backspace (BS)
7
\fASCII Formfeed (FF)
8
\nASCII Linefeed (LF)
9
\rASCII Carriage Return (CR)
10
\tASCII Horizontal Tab (TAB)
11
\vASCII Vertical Tab (VT)
12
\oooCharacter with octal value ooo
13
\xhhCharacter with hex value hh
Escape Characters Example
The following code shows the usage of escape sequences listed in the above table −
# ignore \
s = 'This string will not include \
backslashes or newline characters.'
print(s)# escape backslash
s=s ='The \\character is called backslash'print(s)# escape single quote
s='Hello \'Python\''print(s)# escape double quote
s="Hello \"Python\""print(s)# escape \b to generate ASCII backspace
s='Hel\blo'print(s)# ASCII Bell character
s='Hello\a'print(s)# newline
s='Hello\nPython'print(s)# Horizontal tab
s='Hello\tPython'print(s)# form feed
s="hello\fworld"print(s)# Octal notation
s="\101"print(s)# Hexadecimal notation
s="\x41"print(s)
It will produce the following output −
This string will not include backslashes or newline characters.
The \character is called backslash
Hello 'Python'
Hello "Python"
Helo
Hello
Hello
Python
Hello Python
hello
world
A
A
String formatting in Python is the process of building a string representation dynamically by inserting the value of numeric expressions in an already existing string. Python’s string concatenation operator doesn’t accept a non-string operand. Hence, Python offers following string formatting techniques −
The “%” (modulo) operator often referred to as the string formatting operator. It takes a format string along with a set of variables and combine them to create a string that contain values of the variables formatted in the specified way.
Example
To insert a string into a format string using the “%” operator, we use “%s” as shown in the below example −
name ="Tutorialspoint"print("Welcome to %s!"% name)
It will produce the following output −
Welcome to Tutorialspoint!
Using format() method
It is a built-in method of str class. The format() method works by defining placeholders within a string using curly braces “{}”. These placeholders are then replaced by the values specified in the method’s arguments.
Example
In the below example, we are using format() method to insert values into a string dynamically.
str="Welcome to {}"print(str.format("Tutorialspoint"))
On running the above code, it will produce the following output −
Welcome to Tutorialspoint
Using f-string
The f-strings, also known as formatted string literals, is used to embed expressions inside string literals. The “f” in f-strings stands for formatted and prefixing it with strings creates an f-string. The curly braces “{}” within the string will then act as placeholders that is filled with variables, expressions, or function calls.
Example
The following example illustrates the working of f-strings with expressions.
item1_price =2500
item2_price =300
total =f'Total: {item1_price + item2_price}'print(total)
The output of the above code is as follows −
Total: 2800
Using String Template class
The String Template class belongs to the string module and provides a way to format strings by using placeholders. Here, placeholders are defined by a dollar sign ($) followed by an identifier.
Example
The following example shows how to use Template class to format strings.
from string import Template
# Defining template stringstr="Hello and Welcome to $name !"# Creating Template object
templateObj = Template(str)# now provide values
new_str = templateObj.substitute(name="Tutorialspoint")print(new_str)
String concatenation in Python is the operation of joining two or more strings together. The result of this operation will be a new string that contains the original strings. The diagram below shows a general string concatenation operation −
In Python, there are numerous ways to concatenate strings. We are going to discuss the following −
Using ‘+’ operator
Concatenating String with space
Using multiplication operator
Using ‘+’ and ‘*’ operators together
String Concatenation using ‘+’ operator
The “+” operator is well-known as an addition operator, returning the sum of two numbers. However, the “+” symbol acts as string concatenation operator in Python. It works with two string operands, and results in the concatenation of the two.
The characters of the string on the right of plus symbol are appended to the string on its left. Result of concatenation is a new string.
Example
The following example shows string concatenation operation in Python using + operator.
String 1: Hello
String 2: World
String 3: Hello World
String Concatenation By Multiplying
Another symbol *, which we normally use for multiplication of two numbers, can also be used with string operands. Here, * acts as a repetition operator in Python. One of the operands must be an integer, and the second a string. The integer operand specifies the number of copies of the string operand to be concatenated.
Example
In this example, the * operator concatenates multiple copies of the string.
newString ="Hello"*3print(newString)
The above code will produce the following output −
HelloHelloHello
String Concatenation With ‘+’ and ‘*’ Operators
Both the repetition operator (*) and the concatenation operator (+), can be used in a single expression to concatenate strings. The “*” operator has a higher precedence over the “+” operator.
Example
In the below example, we are concatenating strings using the + and * operator together.
To form str3 string, Python concatenates 3 copies of World first, and then appends the result to Hello
String 3: HelloWorldWorldWorld
In the second case, the strings str1 and str2 are inside parentheses, hence their concatenation takes place first. Its result is then replicated three times.
String 4: HelloWorldHelloWorldHelloWorld
Apart from + and *, no other arithmetic operators can be used with string operands.
String modification refers to the process of changing the characters of a string. If we talk about modifying a string in Python, what we are talking about is creating a new string that is a variation of the original one.
In Python, a string (object of str class) is of immutable type. Here, immutable refers to an object thatcannotbe modified in place once it’s created in memory. Unlike a list, we cannot overwrite any character in the sequence, nor can we insert or append characters to it directly. If we need to modify a string, we will use certain string methods that return anewstring object. However, the original string remains unchanged.
We can use any of the following tricks as a workaround to modify a string.
Converting a String to a List
Both strings and lists in Python are sequence types, they are interconvertible. Thus, we can cast a string to a list, modify the list using methods like insert(), append(), or remove() and then convert the list back to a string to obtain a modified version.
Suppose, we have a string variable s1 with WORD as its value and we are required to convert it into a list. For this operation, we can use the list() built-in function and insert a character L at index 3. Then, we can concatenate all the characters using join() method of str class.
Example
The below example practically illustrates how to convert a string into a list.
original string: WORD
['W', 'O', 'R', 'L', 'D']
Modified string: WORLD
Using the Array Module
To modify a string, construct an array object using the Python standard library named array module. It will create an array of Unicode type from a string variable.
Example
In the below example, we are using array module to modify the specified string.
import array as ar
# initializing a string
s1="WORD"print("original string:", s1)# converting it to an array
sar=ar.array('u', s1)# inserting an element
sar.insert(3,"L")# getting back the modified string
s1=sar.tounicode()print("Modified string:", s1)
It will produce the following output −
original string: WORD
Modified string: WORLD
Using the StringIO Class
Python’s io module defines the classes to handle streams. The StringIO class represents a text stream using an in-memory text buffer. A StringIO object obtained from a string behaves like a File object. Hence we can perform read/write operations on it. The getvalue() method of StringIO class returns a string.
Example
Let us use the above discussed principle in the following program to modify a string.
Python String slicing is a way of creating a sub-string from a given string. In this process, we extract a portion or piece of a string. Usually, we use the slice operator “[ : ]” to perform slicing on a Python String. Before proceeding with string slicing let’s understand string indexing.
In Python, a string is an ordered sequence of Unicode characters. Each character in the string has a unique index in the sequence. The index starts with 0. First character in the string has its positional index 0. The index keeps incrementing towards the end of string.
If a string variable is declared as var=”HELLO PYTHON”, index of each character in the string is as follows −
Python String Indexing
Python allows you to access any individual character from the string by its index. In this case, 0 is the lower bound and 11 is the upper bound of the string. So, var[0] returns H, var[6] returns P. If the index in square brackets exceeds the upper bound, Python raises IndexError.
Example
In the below example, we accessing the characters of a string through index.
var ="HELLO PYTHON"print(var[0])print(var[7])print(var[11])print(var[12])
On running the code, it will produce the following output −
H
Y
N
ERROR!
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
IndexError: string index out of range
Python String Negative & Positive Indexing
One of the unique features of Python sequence types (and therefore a string object) is that it has a negative indexing scheme also. In the example above, a positive indexing scheme is used where the index increments from left to right. In case of negative indexing, the character at the end has -1 index and the index decrements from right to left, as a result the first character H has -12 index.
Example
Let us use negative indexing to fetch N, Y, and H characters.
var ="HELLO PYTHON"print(var[-1])print(var[-5])print(var[-12])
On executing the above code, it will give the following result −
N
Y
H
We can therefore use positive or negative index to retrieve a character from the string.
In Python, string is an immutable object. The object is immutable if it cannot be modified in-place, once stored in a certain memory location. You can retrieve any character from the string with the help of its index, but you cannot replace it with another character.
Example
In the following example, character Y is at index 7 in HELLO PYTHON. Try to replace Y with y and see what happens.
var="HELLO PYTHON"
var[7]="y"print(var)
It will produce the following output −
Traceback (most recent call last):
File "C:\Users\users\example.py", line 2, in <module>
var[7]="y"
~~~^^^
TypeError: 'str' object does not support item assignment
The TypeError is because the string is immutable.
Python String Slicing
Python defines “:” as string slicing operator. It returns a substring from the original string. Its general usage is as follows −
substr=var[x:y]
The “:” operator needs two integer operands (both of which may be omitted, as we shall see in subsequent examples). The first operand x is the index of the first character of the desired slice. The second operand y is the index of the character next to the last in the desired string. So var(x:y] separates characters from xth position to (y-1)th position from the original string.
var: HELLO PYTHON
var[3:8]: LO PY
var[-9:-4]: LO PY
Default Values of Indexes with String Slicing
Both the operands for Python’s Slice operator are optional. The first operand defaults to zero, which means if we do not give the first operand, the slice starts of character at 0th index, i.e. the first character. It slices the leftmost substring up to “y-1” characters.
Example
In this example, we are performing slice operation using default values.
Naturally, if both the operands are not used, the slice will be equal to the original string. That’s because “x” is 0, and “y” is the last index+1 (or -1) by default.
The left operand must be smaller than the operand on right, for getting a substring of the original string. Python doesn’t raise any error, if the left operand is greater, bu returns a null string.
In Python, a string is an immutable sequence of Unicode characters. Each character has a unique numeric value as per the UNICODE standard. But, the sequence as a whole, doesn’t have any numeric value even if all the characters are digits. To differentiate the string from numbers and other identifiers, the sequence of characters is included within single, double or triple quotes in its literal representation. Hence, 1234 is a number (integer) but ‘1234’ is a string.
Creating Python Strings
As long as the same sequence of characters is enclosed, single or double or triple quotes don’t matter. Hence, following string representations are equivalent.
Example
>>>'Welcome To TutorialsPoint''Welcome To TutorialsPoint'>>>"Welcome To TutorialsPoint"'Welcome To TutorialsPoint'>>>'''Welcome To TutorialsPoint''''Welcome To TutorialsPoint'>>>"""Welcome To TutorialsPoint"""'Welcome To TutorialsPoint'
Looking at the above statements, it is clear that, internally Python stores strings as included in single quotes.
In older versions strings are stored internally as 8-bit ASCII, hence it is required to attach ‘u’ to make it Unicode. Since Python 3, all strings are represented in Unicode. Therefore, It is no longer necessary now to add ‘u’ after the string.
Accessing Values in Strings
Python does not support a character type; these are treated as strings of length one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example −
When the above code is executed, it produces the following result −
var1[0]: H
var2[1:5]: ytho
Updating Strings
You can “update” an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether. For example −
Following table is a list of escape or non-printable characters that can be represented with backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
Backslash notation
Hexadecimal character
Description
\a
0x07
Bell or alert
\b
0x08
Backspace
\cx
Control-x
\C-x
Control-x
\e
0x1b
Escape
\f
0x0c
Formfeed
\M-\C-x
Meta-Control-x
\n
0x0a
Newline
\nnn
Octal notation, where n is in the range 0.7
\r
0x0d
Carriage return
\s
0x20
Space
\t
0x09
Tab
\v
0x0b
Vertical tab
\x
Character x
\xnn
Hexadecimal notation, where n is in the range 0.9, a.f, or A.F
String Special Operators
Assume string variable a holds ‘Hello’ and variable b holds ‘Python’, then −
Operator
Description
Example
+
Concatenation – Adds values on either side of the operator
a + b will give HelloPython
*
Repetition – Creates new strings, concatenating multiple copies of the same string
a*2 will give -HelloHello
[]
Slice – Gives the character from the given index
a[1] will give e
[ : ]
Range Slice – Gives the characters from the given range
a[1:4] will give ell
in
Membership – Returns true if a character exists in the given string
H in a will give 1
not in
Membership – Returns true if a character does not exist in the given string
M not in a will give 1
r/R
Raw String – Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter “r,” which precedes the quotation marks. The “r” can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark.
print r’\n’ prints \n and print R’\n’prints \n
%
Format – Performs String formatting
See at next section
String Formatting Operator
One of Python’s coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C’s printf() family. Following is a simple example −
Open Compiler
print("My name is %s and weight is %d kg!"%('Zara',21))
When the above code is executed, it produces the following result −
My name is Zara and weight is 21 kg!
Here is the list of complete set of symbols which can be used along with % −
Sr.No.
Format Symbol & Conversion
1
%ccharacter
2
%sstring conversion via str() prior to formatting
3
%isigned decimal integer
4
%dsigned decimal integer
5
%uunsigned decimal integer
6
%ooctal integer
7
%xhexadecimal integer (lowercase letters)
8
%Xhexadecimal integer (UPPERcase letters)
9
%eexponential notation (with lowercase ‘e’)
10
%Eexponential notation (with UPPERcase ‘E’)
11
%ffloating point real number
12
%gthe shorter of %f and %e
13
%Gthe shorter of %f and %E
Other supported symbols and functionality are listed in the following table −
Sr.No.
Symbol & Functionality
1
*argument specifies width or precision
2
–left justification
3
+display the sign
4
<sp>leave a blank space before a positive number
5
#add the octal leading zero ( ‘0’ ) or hexadecimal leading ‘0x’ or ‘0X’, depending on whether ‘x’ or ‘X’ were used.
6
0pad from left with zeros (instead of spaces)
7
%‘%%’ leaves you with a single literal ‘%’
8
(var)mapping variable (dictionary arguments)
9
m.n.m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)
You want to embed some text in double quotes as a part of string, the string itself should be put in single quotes. To embed a single quoted text, string should be written in double quotes.
Example
var ='Welcome to "Python Tutorial" from TutorialsPoint'print("var:", var)
var ="Welcome to 'Python Tutorial' from TutorialsPoint"print("var:", var)
It will produce the following output −
var: Welcome to "Python Tutorial" from TutorialsPoint
var: Welcome to 'Python Tutorial' from TutorialsPoint
Triple Quotes
To form a string with triple quotes, you may use triple single quotes, or triple double quotes − both versions are similar.
Example
var ='''Welcome to TutorialsPoint'''print("var:", var)
var ="""Welcome to TutorialsPoint"""print("var:", var)
It will produce the following output −
var: Welcome to TutorialsPoint
var: Welcome to TutorialsPoint
Python Multiline Strings
Triple quoted string is useful to form a multi-line string.
Example
var ='''
Welcome To
Python Tutorial
from TutorialsPoint
'''print("var:", var)
It will produce the following output −
var:
Welcome To
Python Tutorial
from TutorialsPoint
Arithmetic Operators with Strings
A string is a non-numeric data type. Obviously, we cannot use arithmetic operators with string operands. Python raises TypeError in such a case.
print("Hello"-"World")
On executing the above program it will generate the following error −
>>> "Hello"-"World"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'
Getting Type of Python Strings
A string in Python is an object of str class. It can be verified with type() function.
Example
var ="Welcome To TutorialsPoint"print(type(var))
It will produce the following output −
<class 'str'>
Built-in String Methods
Python includes the following built-in methods to manipulate strings −
casefold()Converts all uppercase letters in string to lowercase. Similar to lower(), but works on UNICODE characters alos.
3
center(width, fillchar)Returns a space-padded string with the original string centered to a total of width columns.
4
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.
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’.
7
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.
8
expandtabs(tabsize=8)Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.
9
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.
rjust(width,[, fillchar])Returns a space-padded string with the original string right-justified to a total of width columns.
37
rpartition()Splits the string in three string tuple at the ladt occurrence of separator.
38
rsplit()Splits the string from the end and returns a list of substrings.
39
rstrip()Removes all trailing whitespace of string.
40
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.
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.
43
strip([chars])Performs both lstrip() and rstrip() on string.
title()Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase.
46
translate(table, deletechars=””)Translates string according to translation table str(256 chars), removing those in the del string.
47
upper()Converts lowercase letters in string to uppercase.
48
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).
Built-in Functions with Strings
Following are the built-in functions we can use with strings −