What is Strings in Python? 

What is Strings in Python? 

In Python, Strings are sequences of characters. A string is a sequence of Unicode characters. Unicode was introduced to include every character in all languages and bring uniformity in encoding. Python features a built-in string class named “str” with many handy features. String literals are often enclosed by either double or single quotes, although single quotes are more commonly used. Backslash escapes work the standard way within both single and double quoted literals.

We discuss in detail about strings and what are the possible operations that we can perform on strings.  

Learning Outcomes 

  • Define and Use strings in Python
  • Learn how to access strings
  • Understand and use different operations which we can perform on strings
  1. Strings are sequences of characters.  
  1. In Python, a  string is a sequence of Unicode characters.   
  1. Unicode was introduced to include every character in all languages and bring uniformity in encoding.  
  1. Python features a built-in string class named “str” with many handy features. 
  1. String literals are often enclosed by either double or single quotes, although single quotes are more commonly used. Backslash escapes work the standard way within both single and double quoted literals.  
  1. A string literal can span multiple lines, but there must be a backslash \ at the top of every line to flee the new line.  
  1. String literals inside triple quotes, “‘or”””, can span multiple lines of text. Python strings are “immutable” which means they can’t be changed after they are created (Java strings also use these immutable style). Since strings cannot be changed. So for instance th(‘dear’ + ‘students’) takes within the 2 strings ‘dear’ and ‘students’ and builds a replacement strings ‘dearstudents’. 
  1. In Python, individual characters of a string can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, example -1 refers to the last character, -2 refers to the second last character and so on. 
  1. While accessing an index out of the range will cause an Index Error. Only Integers are allowed to be passed as an index, float or other types will Causeway a Type Error
  1. To access a range of characters in the String, method of slicing is used. Slicing in a String is done by using a Slicing operator (colon).  
  1. Strings in Python can be formatted with the use of format () method which is very versatile and powerful tool for formatting of the Strings. Format method in String contains curly braces {} as placeholders which can hold arguments and according to position or keywords to specify the order.  

1.1 HOW TO CREATE A STRING IN PYTHON? 

Strings are often created by enclosing characters inside single quote or double quotes. Even triple quotes are often used in Python for multiline statements and doc strings.  

# Creating a string with single quotes 

String 1 = ‘stay at home’  

print (String1)  

# creating a string with double quotes  

String 2 = “Python programming is fun to learn”  

Print (Strings 2)  

After executing above code using print method you will get the following output: 

Stay at home  

Python programming is fun to learn   

In Python you can use triple quotes along with variable names  

Read_books = ‘Saturday’  

Watching_movies = ‘Sunday’ 

String 1 = “”” I like to read books on %Read_books  

I like to watching movies on %watching_movies””””  

Print (String 1) 

Output: 

I like to read books on Saturday  

I like to watching movies on Sunday. 

1.2 LENGTH OF A STRING: 

Using Python string len () method you can compute the length of the given string.  

Description  

Python string method len () returns the length of the string.  

Parameters:  

It takes string as the parameter.  

Return Value:  

It returns an integer which is the length of the string.  

Syntax:  

Following is the syntax for len() method “  

learn (str) 

Examples:  

Str1=”welcome to Python programming”  

print “Length of the string is.” len(str1)   

Output:  

It will display string length as output as follows  

Length of the string is 28. 

Methods to compute the string length:

  1. You can compute the length of a string with built in functions

#Python code to demonstrate string length

#using len

str = “welcome to world of python”

print (len(str))

output :26

2. Using for loop and in operator:

A string can be iterated over, directly in a for loop. Maintaining a count of the number of iterations will result in the length of the string.

#Python code to demonstrate string length

#using for loop

#Returns length of string

def findLen (str):

counter = 0

for i in str:

counter += 1

return counter

str = “stay home”

print(findLen(str))

Output:9

3. Using while loop and Slicing.

We slice a string making it shorter by 1 at each iteration will eventually result in an empty string. This is when while loop stops. Maintaining a count of the number of iterations will result in the length of the string.

#Returns code to demonstrate string length

#using while loop

#Returns length of string

def findLen(str):

counter = 0

while str[counter:]:

counter +=1

return counter

str = “stay home”

print(findLen(str))

Output: 9

1.3 Concatenation of strings:

In Python,you can concatenate two different strings together and also the same string to itself multiple times using + and the *operator respectively.

Use the + operator

The + operator can be used to concatenate two different string.

Below code concatenation two strings from s1 and s2

s1 =”welcome to”

s2 =”Python Programming:

print (“String1 :”,s1)

print (“String2:”,s2)

s=s1+s2

print(“Concatenated two different strings:”,s)

String 1: welcome to

String 2: Python Programming

Concatenated two different strings: welcome to Python Programming

Use the * operator(repeat operation)

Appending the same string to a string can be done using the * operator, as follows:

str=str * x

Where x is the number of times string str is appended to itself.

Sample code for above illustration:

str1=”Welcome”

print (string 1 :”, str 1)

str1=str1*5

print(“Concatenated same string:”,str1)

Output:

Welcome

Concatenated same string:WelcomeWelcomeWelcomeWelcomeWelcome

1.4 Indexing and Slicing

Strings are Arrays

Like many other popular programming language, strings in Python are arrays of bytes representing Unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1.

Strings in python support indexing and slicing. To exact a single character from a string, follow the string with the index of the desired character surrounded by square brackets ([ ]), remembering that the first character of a string has index zero.

>>> str =’Python is my favourite programming language’

>>>str[4]

‘0’

>>>str[0]

‘P’

Indexing:

You can give indexing in both ways it means from left to right start with 0 and increment by 1 and if you start from right to left start negative indexing with -1 and decrement by -1,-2,-3 etc.

Accessing Characters by Positive Index Number

Str = ” SRINIVAS”

By referencing index numbers, we can isolate one of the characters in a string. We do this by putting the index numbers in square brackets. Let’s declare a string, print it, and call the index number in square brackets:

Str =”SRINIVAS”

print(Str[4])

Output:1

Accessing Characters by Negative Index Number

Str = “SRINIVAS”

print(Str[-3])

Output: V

Python Slice()

The slice() function returns a slice object that can use used to slice strings, lists,tuple etc.

The slice object is used to slice a given sequence (string, bytes, tuple, list or range) or any object which supports sequence protocol (implements _getitem_() and _len_() method).

The syntax of slice() is:

Slice(Start, stop, step)

Slice() Parameters:

Slice() can take three parameters:

Start (optional) – Starting integer where the slicing of the object starts. Default to None if not provided.

Stop – Integer until which the slicing takes place. The slicing stops at index stop -1 (last element).

Stop (Optional)- Integer value which determines the increment between each index for slicing. Defaults to None if not provided.

Here are some strings slicing examples:

>>> str = ‘PYTHON’

>>>str[2:5]

‘THO’

>>>str[0:2]

‘PY’

>>>str[1:4]

‘YTH’

You can omit the first or last index:

>>> str =’PYTHON’

>>>str[:2] Here start is optional it means it will start from index 0 upto last index -1.

‘PY’

>>>str[:5] It will slice up to from index 0.

‘PYTHO’

>>> str[2:] + str[2:] Concatenation of two slices

‘PYTHON’

>>>s[:] Here start and end is optional (ignored) it means it will print complete string.

‘PYTHON’

Here’s some negative index slicing:>>> str =’PYTHON’

>>>str[-5:-1]

‘YTHON’

Here’s how to slice with a stride:

>>> str = ‘welcome’

>>>str[0:7:2]

‘wloe’

>>>s[1:7:2]

‘ecm’

Additionally, you can indicate a negative numeric value for the stride, which we can use to print the original string in reverse order if we set the stride to -1:

Str=”welcome”

print(str[::-1])

output:emoclew

Python Format Characters

String ‘%’ operator issued for formatting Strings. We often use this operator with the print() function.

Here’s a simple example.

print (“Student Name: %s, \nStudent Age:%d” % (‘SAYONAH’,20))

# Student Name: Sayonah,

# Student Age: 20

List of Format Symbols

Following is the table containing the complete list of symbols that you can use with the ‘%’ operator.

Symbol Conversion

%C Character

%S String conversion via str () before formatting

%i signed decimal integer

%d signed decimal integer

%u unsigned decimal integer

%o octal integer

%x hexadecimal integer (lowercase letters)

%X hexadecimal integer (UPPER-case letters)

%e exponential notation (with lowercase ‘e’)

%E exponential notation (with UPPER-case ‘E’)

%f floating-point real number

%g the shorter of %f and %e

%G the shorter of %f and %E

Built-in string methods in Python:

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 code registered for encoding, encoding defaults to the default string encoding.

5. encode(encoding=’UTF-8′,errors=’strict’)

Returns encoded string version of the 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 tab in string to multiple spaces.;defaults to 8 spaces per tab if tab size not provided. 

8. find (str, beg=0 end-len(string)) 

Determine if str occurs in a 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 lower case 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 strings 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 are 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 strings 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 a 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.. 

Python program using built-in string method ()

Frequently Asked Questions (FAQ)

  1. How to create a string in Python? 
  1. How to find the maximum occurring character in given string? (e.g.,if the input string is “Java” then the function should return ‘a’.) 
  1. How to find the index of a character in a string in Python? 
  1. What is string slicing in python? Give one example
  1. How to print reverse of a string using Python? 
  1. Write a program to print every character of a string entered by user in a new line using len function. 
  1. Write a program to find the length of the string “Programming” without using len function. 
  1. Write a program to check if the letter ‘e’ is present in the word ‘Welcome’. 
  1. Write a program to check if the word ‘python’ is present in the “Welcome to python programming”. 
  1. Write a program to find the first and the last occurrence of the letter ‘o’ and character ‘,’ in “Hello, World”. 
  1. Write the string after the first occurrence of ‘,’ and the string after the last occurrence of, ‘,’ in the string “Hello, Good, Morning”. World”. 
  1. Write a program that takes your full name as input and displays the abbreviations of the first and middle names except the last name which is displayed as it is. For example, if your name is Mahendra Singh Dhoni, then the output should be M.S. Dhoni. 
  1. Write a program to find the number of vowels, consonents, digits, and whitespace characters in a string. 
  1. Write a program to make a new string with all the consonents deleted from the string “Hello, have a good day”. 
  1. Write a Python program to get a string from a given string where all occurrences of its first char have been changed to ‘$’, except the first char itself.

Know More: https://procomputereducation.com/fundamentals-of-python-programming/

Read More: https://youtu.be/t1IwCfXbtFw

Leave a Comment