1. Define a string in Python

Like all other programming languages, strings in python is a sequence of Unicode characters taken as a Python variable in the form of expressions surrounded by single quotes or double quotes. For example "Python Programming" is a Python string identical to 'Python Programming'.

Python Strings can be displayed on screen using the print() function:

print(name_of_the_string_variable)

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"

s = "Python"
print("The length of the string s is:", len(s)) 
# output: The length of the string s is: 6

3. Accessing the elements of a Python string

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

s[character_index]

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):

s = "Python Programming"
print("the first character of s is: ", s[0])
# displays: "the first character of s is 'P'
print("the second character of s is: ", s[1])
# displays:"the second character of s is 'y'

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

s="Python"
for i in range(0 , len(s)):
    print(s[i])
# attach:
"""
P
y
t
h
o
n
"""

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

s="Python"
for x in s:
    print(x)
# output:
"""
P
y
t
h
o
n
"""

4. Python String Operations

4.1 Concatenation of two Python string characters

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

Example

s1 = "Python"
s2 = "Programming"
# concatenation of s1 and s2
s = s1 + s2
print(s) # output: 'Python Programming'

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:

substring = string[i:j]

Example

s = "Python"
substring = s[1:4]
print(substring) # output: 'yth'

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

s = "CRMEF OUJDA"
s = s.lower ()
print (s) # displays crmef oujda

Example. replacing one occurrence with another

s = "CRMEF OUJDA"
s = s.replace ("CRMEF", "ENS")
print (s) # display: ENS OUJDA

Example. Number of characters in a string

s = "CRMEF OUJDA"
n = len(s)
print ("the number of characters in the string s is:", n)
# displays the number of characters in the string s is: 11

Example. String.format

name = "David"
age = 37
s = 'Hello, {}, you have {} ans'.format (name, age)
print (s) # display:  'Hello, David, you are 37'

Example. extract a sub string

s = "CRMEF OUJDA"
s1 = s [6: 9]
print (s1) # displays OUJ
s2 = s [6:]
print (s2) # displays OUJDA
s3 = s [: 4]
print (s3) # displays CRME

 

Younes Derfoufi
my-courses.net

Leave a Reply