String Variable In Python

1. Define a string in Python

In Python, a string is a sequence of characters enclosed within single quotes ('') or double quotes (""). It is one of the built-in data types in Python and is used to represent textual data. Strings are immutable! which means that once created, their content cannot be changed. However, you can perform various operations on strings to manipulate and extract information from them.
Here's an overview of some important characteristics and operations related to Python strings:
Declaration and Initialization:
You can declare and initialize a string variable by assigning a sequence of characters to it using quotes. For example:

Like many other popular programming languages, strings in Python are byte arrays representing Unicode characters. However, Python does not have a character (char) data type like char type in C, a single character is simply a string of length 1. Square brackets can be used to access string elements.

2. Length of a Python string

The length of a character string is by definition the number of characters that make up the string. To get the length of a string, we use the len() method.

Example: length of the string s = "Python"

3. Accessing the elements of a Python string

To access an element of a character string s, we use the syntax:

Example

Let's have fun displaying the first and second character of the string: s = "Python Programming"
(remember that the first character is at position 0):

Example: displaying all characters of a string using the len() method

Example: displaying total characters of a string via the iterator method

4. Python String Operations

4.1 Concatenation of two Python string characters

To concatenate two string characters in python, we use the '+' operator:

Example

4.2 Extract a substring

We extract a substring of a string s from the ith position up to the jth not included using the syntax:

Example

5. The main methods associated with character strings in Python

The Python language is equipped with a large number of functions allowing the manipulation of string characters: calculation of the length of the string, transformation into upper and lower case, extracting a sub-string... Here is a non-exhaustive list:

Here is a non-exhaustive list:

1. capitalize ():   capitalize the first letter of the string
2. center (width, fill):   returns a string filled with spaces with the original string centered on the total width columns.
3. counts (str, beg = 0, end = len (string)):   counts the number of times str occurs in a string or a substring if the start of the start index and the end of the end index are indicated.
4. decode (encoding = 'UTF-8', errors = 'strict'):   decodes the string using the codec recorded for encoding. The default encoding is the default string encoding.
5. encode (encoding = 'UTF-8', errors = 'strict'):   returns the encoded version of the string; in case of error, the default value is to generate a ValueError value unless errors are indicated with "ignore" or "replace".
6. endswith (suffix, start = 0, end = len (string)):   determines whether a string or a substring string (if end indexes start and end indexes are indicated) ends with a suffix; returns true if yes and false otherwise.

 

7. expandtabs (tabsize = 8):   expands the tabs of a string into multiple spaces; The default value is 8 spaces per tab if tabsize is not provided.
8. find (str, beg = 0 end = len (string)):   determine if str appears in a string or a substring of strings if the start index and end index are specified, end returns if it is found and -1 otherwise.
9. format (string s):   replace the braces by the variable string s (see example below: [String.format])
10. index (str, beg = 0, end = len (string)):   same as find (), but raises an exception if str is not found.
11. isalnum ():   returns true if the string is at least 1 character and all characters are alphanumeric and false otherwise.
12. isalpha ():   returns true if the string has at least 1 character and all characters are alphabetic and false otherwise.
13. isdigit ():   returns true if the string contains only numbers and false otherwise.
14. islower ():   returns true if the string has at least 1 character in case and all case characters are lowercase and false otherwise.
15. isnumeric ():   returns true if a unicode string contains only numeric characters and false otherwise.
16. isspace ():   returns true if the string contains only space characters and false otherwise.
17. istitle ():   returns true if the string is correctly titlecased and false otherwise.
18. isupper (): Returns true if string contains at least one character and all characters are uppercase and false otherwise.
19. join (seq):   merges (concatenates) the string representations of elements in sequence seq into a string, with a separator string.
20. len (string):   returns the length of the string
21. ljust (width [, padding]):   returns a string filled with spaces with the original justified string to the left for a total of width columns.
22. lower ():   converts all uppercase letters in a string to lowercase.
23. lstrip ():   removes all spaces at the beginning of the string.
24. maketrans():   returns a translation table to use in the translation function.
25. max (str):    returns the maximum alphabetic character of string str.
26. min (str):   returns the minimum alphabetic character of string str.
27. replace (old, new [, max]):   replaces all occurrences of old in string with new or maximum max if given max.
28. rfind (str, beg = 0, end = len (string)):   same as find (), but look back in string.
29. rindex (str, beg = 0, end = len (string)):   same as index (), but look back in string.
30. rjust (width, [, padding]):   returns a string filled with spaces with the justified origin string on the right, with a total of width columns.
31. rstrip ():   removes all trailing spaces.
32. split (str = "", num = string.count (str)):   divides the string according to the str (if not supplied) delimiter and returns the list of substrings; divided into maximum substrings, if any.
33. splitlines (num = string.count (' n')):   breaks the string of all NEWLINE (or num) and returns a list of each line without the NEWLINE.
34. startswith (str, beg = 0, end = len (string)):   determines whether string or a substring string (if end indexes and end indexes are specified) begins with the sub-string string str; returns true if yes and false otherwise.
35. strip ([floats]):   performs lstrip () and rstrip () on string.
36. swapcase ():   reverses the case of all letters

6. Example of using string functions

Example. transformation of a string into lower case

Example. replacing one occurrence with another

Example. Number of characters in a string

Example. String.format

Example. extract a sub string

 

Younes Derfoufi
CRMEF OUJDA

Leave a Reply