Strings in Python

Overview:

  • Strings are used for representing and processing texts of arbitrary length.
  • In other programming languages like C, C++ and Java there is a separate type representing characters. In those languages strings are collection of characters.
  • In Python there is no separate type to represent characters.
  • Python strings are a collection of code points.
  • In Python, individual characters as well, are represented as strings.
  • Strings are immutable in Python.
  • Strings in Python are of type str which is a built-in class in Python.

   

String Construction:   

Strings literals can be constructed in multiple ways using:

  • Single quotes
  • Double quotes
  • Triple quotes
  • Constructor

 

Single Quoted Python Strings Vs Double Quoted Python Strings:

In Python, there is no difference between strings constructed using single quotes and double quotes. It is good if the developer could stick to one convention.

If a string contains a single quote or double quote - use the other one to avoid escaping it with a backslash, which improves readability.

Triple Quoted Strings:

Triple quoted strings are used to provide string literals that span across multiple lines in a Python Program. All the white spaces are taken as part of the string literal. Triple quoted strings are also used as docstrings in a Python Program.

 

Using str constructor:

The str constructor function takes a collection of unicode points(ie., characters) enclosed by single/double/triple quotes.

Another variant of the str() constructor takes encoding and the error handling scheme as parameters to it.

 

Example:

sampleString = str("Universe is Big")

 

# Convert the string to lower case

lowerCase = sampleString.lower()

print("String converted to lower case:{}".format(lowerCase))

 

 

# Capitalize only the first letter

capitalized = sampleString.capitalize()

print("String with first letter capitalized:{}".format(capitalized))

 

# Find the length of the string

stringLength = len(sampleString)

print("String length:{}".format(stringLength))

 

# Check if all the characters all alphabets

alphaCheck = sampleString.isalpha()

 

# False as the string has space characters

print("All the characters all alphabets:{}".format(alphaCheck))

 

 

 

Output:

String converted to lower case:universe is big

String with first letter capitalized:Universe is big

String length:15

All the characters all alphabets:False

 

String Methods:

The str class in Python provides a collection of methods to process strings. The str methods are listed here as a table.

 

Method Name

Responsibility

capitalize()

Returns a copy of the string instance with the following modifications done

  • Capitalize the first character
  • Make all the other characters as lower case

casefold()

  • Returns a copy of the string, which is casefolded.
  • Casefolding is a more aggressive form of lowercasing.

center(width[, fillchar])

  • This method does not return the central character or any central part of the string.
  • On a string with “n” as length,  center() will make the original string appear in the center portion.
  • Remaining portion of the string will be padded with specified padding character.

count(sub[, start[, end]])

  • Returns the number of times a substring appears in a given string object.

encode(encoding="utf-8", errors="strict")

  • Returns a byte array corresponding to the characters (i.e., codepoints)

Present in the string.

endswith(suffix[, start[, end]])

  • endswith() returns True if a string ends with the specified suffix and returns False otherwise.
  • A list of strings from a tuple as well could be provided as parameter instead of a single string.
  • endswith() accepts start and stop position for the search.
find(sub[, start[, end]])
  • In a given string object, find() returns the lowest position of a specified substring.
index(sub[, start[, end]])
  • The index() method returns the lowest position at which a substring is found. Raises a ValueError otherwise.
isalnum()
  • isalnum() checks whether a string is absolutely aplhanumeric, meaning if any non-alphanumeric characters found will return false.
  • Will return true only if the whole string is made of digits and alphabets.

isalpha()

  • The isalpha() method returns true if a string object is solely made of alphabets;
  • returns false otherwise; 
  • isalpha() returns false for empty strings.
isidentifier()
  • The isidentifier() method returns True if the string contents form a valid python identfier name; returns False otherwise.
islower()
  • islower() method will return True if all the characters in a string object are lower cased.
  • islower() returns False if at least one character present in the string is not lower cased.
  • If a string is an empty string, islower() retruns false.

 


Copyright 2024 © pythontic.com