1 - Define string in Python
A string variable in Python is sequence of characters that follow each other and delimited by double or single quotas "..." or '...'. A string which does not contain any characters is called an empty string.Example
s1 = "Hello !"
s2 = 'welcome !'
print(s1) # this will display :
Hello print(s2) # this will display : welcome
2 - Access the elements of a string variable
The brackets can be used to access the string elements.Example. get the character at position 1
(remember that the first character has the 0 position):
s = "Hello World!"
print ("The second character of s is:", s [1])
# this will displays: "The second character of s is: e
Note:
A string is immutable: once it is created, its content can not be changed.Example
s = "welcome" s [1] = v # causes a run-time error, indicating that it is impossible to change the contents of a string
3 - Python functions for string object
The Python language is endowed with a large number of functions allowing the manipulation of chains of characters: calculation of the length of the chain, transformation in upper and lower case, to extract a sosus chain ...
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
4 - 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
No comments:
Post a Comment