What is a String?
A string is a sequence of characters. A character is simply a symbol. For example, the English language has 26 characters. Computers do not deal with characters, they deal with numbers (binary). Even though you may see characters on your screen, internally it is stored and manipulated as a combination of 0’s and 1’s. This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and Unicode are some of the popular encoding used. In Python, string is a sequence of Unicode character. Unicode was introduced to include every character in all languages and bring uniformity in encoding.
Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable.
For example −
var1 = ‘Hello World!’
var2 = “Python Programming"
var3 = "’This is also valid"’
var4 = “""So is this"""
String operations and indices
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 −
var1 = ‘Hello World!’
var2 = “Python Programming"
print(“var1[0]: “, var1[0])
print(“var2[1:5]: “, var2[1:5])
When the above code is executed, it produces the following result:
var1[0]: H
var2[1:5]: ytho
If we try to access index out of the range or use decimal number, we will get errors.
# index must be in range
>>> my_string[15]
…
IndexError: string index out of range
# index must be an integer
>>> my_string[1.5]
…
TypeError: string indices must be integers
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 float 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). Slicing can be best visualized by considering the index to be between the elements as shown below.
If we want to access a range, we need the index that will slice the portion from the string.
Practice Programs:
str = ‘practice python’
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:
Basic String Operations
Delete a string
Operation 1: How to change or delete a string?
Strings are immutable. This means that elements of a string cannot be changed once it has been assigned. We can simply reassign different strings to the same name.
>>> my_string = ‘Python’
>>> my_string[1] = ‘Y’
…
TypeError: ‘str’ object does not support item assignment
>>> my_string = ‘Python’
>>> my_string
‘Python’
We cannot delete or remove characters from a string. But deleting the string entirely is possible using the keyword del.
>>> del my_string[1]
…
TypeError: ‘str’ object doesn’t support item deletion
>>> del my_string
>>> my_string
…
NameError: name ‘my_string’ is not defined
There are many operations that can be performed with string which makes it one of the most used datatypes in Python
String Multiplication and Concatenation
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.
str1 = ‘Hello’
str2 =’World!’
# using +
print(‘str1 + str2 = ‘, str1 + str2)
# using *
print(‘str1 * 3 =’, str1 * 3)
Output:
Concatenation of Two or More Strings Writing two string literals together also concatenates them like + operator. If we want to concatenate strings in different lines, we can use parentheses. >>> # two string literals together >>> ‘Hello "World!’ ‘Hello World!’ >>> # using parentheses >>> s = (‘Hello ‘ … ‘World’) >>> s ‘Hello World’ Iterating Through String Using for loop we can iterate through a string. Here is an example to count the number of ‘l’ in a string.
count = 0
for letter in ‘Hello World’:
if(letter == ‘l’):
count += 1
print(count,’letters found’)
Output: String Membership Test We can test if a sub string exists within a string or not, using the keyword in. >>> ‘a’ in ‘program’ True >>> ‘at’ not in ‘battle’ False Built-in functions to Work with Python Various built-in functions that work with sequence, works with string as well. Some of the commonly used ones are enumerate() and len(). The enumerate() function returns an enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful for iteration. Similarly, len() returns the length (number of characters) of the string.
str = ‘cold’
# enumerate()
list_enumerate = list(enumerate(str))
print(‘list(enumerate(str) = ‘, list_enumerate)
#character count
print(‘len(str) = ‘, len(str))
Output:
String Formatting Operator
Escape Sequence
If we want to print a text like -He said, “What’s there?"- we can neither use single quote or double quotes. This will result into Syntax Error as the text itself contains both single and double quotes.
>>> print(“He said, “What’s there?"")
…
SyntaxError: invalid syntax
>>> print(‘He said, “What’s there?"‘)
…
SyntaxError: invalid syntax
Python String Formatting
One way to get around this problem is to use triple quotes. Alternatively, we can use escape sequences.
An escape sequence starts with a backslash and is interpreted differently. If we use single quote to represent a string, all the single quotes inside the string must be escaped. Similar is the case with double quotes. Here is how it can be done to represent the above text.
# using triple quotes
print("’He said, “What’s there?""’)
# escaping single quotes
print(‘He said, “What’s there?"‘)
# escaping double quotes
print(“He said, “What’s there?"")
Output:
Examples:
>>> print(“C:Python32Lib")
C:Python32Lib
>>> print(“This is printedn in two lines")
This is printed
in two lines
>>> print(“This is x48x45x58 representation")
This is HEX representation
Raw String to ignore escape sequence
Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place r or R in front of the string. This will imply that it is a raw string and any escape sequence inside it will be ignored.
>>> print(“This is x61 ngood example")
This is a
good example
>>> print(r"This is x61 ngood example")
This is x61 ngood example
The format() Method for Formatting Strings
The format() method that is available with the string object is very versatile and powerful in formatting strings.
Format strings contains curly braces {} as placeholders or replacement fields which gets replaced.
We can use positional arguments or keyword arguments to specify the order.
The format() Method for Formatting Strings
# default(implicit) order
default_order = “{}, {} and {}".format(‘John’,’Bill’,’Sean’)
print(‘n— Default Order —‘)
print(default_order)
# order using positional argument
positional_order = “{1}, {0} and {2}".format(‘John’,’Bill’,’Sean’)
print(‘n— Positional Order —‘)
print(positional_order)
# order using keyword argument
keyword_order = “{s}, {b} and {j}".format(j=’John’,b=’Bill’,s=’Sean’)
print(‘n— Keyword Order —‘)
print(keyword_order)
The format() method can have optional format specifications. They are separated from field name using colon. For example, we can left-justify <, right-justify > or center ^ a string in the given space. We can also format integers as binary, hexadecimal etc. and floats can be rounded or displayed in the exponent format. There are a ton of formatting you can use. Visit here for all the string formatting available with the format() method. >>> # formatting integers >>> “Binary representation of {0} is {0:b}".format(12) ‘Binary representation of 12 is 1100’ >>> # formatting floats >>> “Exponent representation: {0:e}".format(1566.345) ‘Exponent representation: 1.566345e+03’ >>> # round off >>> “One third is: {0:.3f}".format(1/3) ‘One third is: 0.333’ >>> # string alignment >>> “|{:<10}|{:^10}|{:>10}|".format(‘butter’,’bread’,’ham’) ‘|butter | bread | ham|’ Old style formatting We can even format strings like the old sprintf() style used in C programming language. We use the % operator to accomplish this.
>>> x = 12.3456789
>>> print(‘The value of x is %3.2f’ %x)
The value of x is 12.35
>>> print(‘The value of x is %3.4f’ %x)
The value of x is 12.3457
Strings Built-In Functions
The strings that you use in program are all objects of the class str . Some useful methods of this class are demonstrated in the next example. For a complete list of such methods, see help(str).
my_string = “Hello World"
print(my_string.isalnum())
#Check if string contains alphabet and numbers only
print(my_string.isalpha())
#Check if string contains only alphabet
print(my_string.isdigit())
Check if string contains only digits
print(my_string.istitle())
#Check if string has Title case – first character word is uppercase
print(my_string.isupper())
#Check if string is in Uppercase
print(my_string.islower())
#Check if string is in lowercase
print(my_string.isspace())
#Check if it contains only blank spaces
print(my_string.endswith(‘d’))
#Check if string ends with d (case sensitive)
print(my_string.startswith(‘h’))
#Check if string starts with h (case sensitive)
Output
False
False
False
True
False
False
False
True
False
In-built functions spported by String:
str.capitalize() : Return a copy of the string with its first character capitalized and the rest lowercased.
str.casefold() : Return a casefolded copy of the string. Casefolded strings may be used for caseless matching. Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter ‘ß’ is equivalent to “ss". Since it is already lowercase, lower() would do nothing to ‘ß’; casefold() converts it to “ss".
str.center(width[, fillchar]) : Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).
str.count(sub[, start[, end]]) : Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
str.find(sub[, start[, end]]) : Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
str.islower() : Return true if all cased characters [4] in the string are lowercase and there is at least one cased character, false otherwise.
str.split() Python string split() function is used to split a string into the list of strings based on a delimiter.
str.join() This function returns a new string that is the concatenation of the strings in iterable with string object as a delimiter.
str.strip() Used to trim whitespaces from the string object.
str.upper() We can convert a string to uppercase in Python using str.upper() function.
str.lower() This function creates a new string in lowercase.
str.replace() Python string replace() function is used to create a new string by replacing some parts of another string.
str.find() Python String find() method is used to find the index of a substring in a string.
str1 = “Yours Truly Learning Center"
print(str1.lower())
print(str1.upper())
print(str1.split())
print(‘ ‘.join([‘This’, ‘will’, ‘join’, ‘all’, ‘words’, ‘into’, ‘a’, ‘string’]))
print(str1.find(‘ear’))
print(str1.replace(‘Center’,’World’))
1. Write a Python program to move spaces to the front of a given string.
Input: Hello from Hyderabad
Output: HellofromHyderabad
2. Write a Python program to compute sum of digits of a given string.
Input: ABC369abc810xyz
Output:27
3. Write a Python program to capitalize first and last letters of each word of a given string.
Input: hello from hyderabad
Output: HellO FroM HyderabaD
4. Write a Python program to print the index of the character in a string.
Input: Hello
Output:
Current character h position at 0
Current character e position at 1
Current character l position at 2
Current character l position at 3
Current character 0 position at 4
5. Write a Python program to swap comma and dot in a string.
Input: 75.99,25.11
Output: 75,99.25,11
Solutions
Solution 1:
inputStr = “Hello from Hyderabad"
noSpacesChars = [ch for ch in inputStr if ch!=’ ‘]
print(noSpacesChars)
spacesCount = len(inputStr) – len(noSpacesChars)
result = ‘ ‘*spacesCount
result = ‘"‘+result + ".join(noSpacesChars)+'"‘
print(result)
Solution 2:
inputStr = “ABC369abc810xyz"
sumDigit = 0
for ch in inputStr:
if ch.isdigit() == True:
chr2int = int(ch)
sumDigit = sumDigit + chr2int
print(“Sum of Digits in the String are: “,sumDigit)
Solution 3:
inputStr = “hello from hyderabad"
inputStr = inputStr.title() #Set to Title Case
result = “"
for word in inputStr.split():
result += word[:-1] + word[-1].upper() + " “
print(result[:-1])
Solution 4:
inputStr = “Hello"
for counter, ch in enumerate(inputStr):
print(“Current character", ch, “position at", counter)
Solution 5:
amount = “75.99,25.11"
amountTrans = amount.maketrans(‘.,’, ‘,.’)
# maketrans() method returns a translation table
# translate
amount = amount.translate(amountTrans)
print(amount)