Social Icons

Thursday, August 15, 2019

String Variable In Python

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

Category Of Mobile Courses

Actualités (644) Adsense (1) Affiliation (1) Algebraic Topology (1) Algorithmic (1) all-news (30) Android (5) Android App (8) Android app without code (4) Android Apps (169) Android Development (4) Android download (2) Android OS (3) AngularJS (1) Automata theory and formal language (5) C programming (5) Category and Functor (8) CMS (3) Computer Glossary (18) Create Mobile App With Ionic Framework (2) CSS (2) CSS-Cascading-Style-Sheets (4) Developpement Java (13) Differential Geometry (1) Django-Python-Framework (8) dropshiping (26) Earn Money by Internet (4) Emplois (23) Framework php (2) Fraud (2) HTML (7) Java For Beginners (10) Javascript (12) Kotlin Programming Language (8) Kotlin For Mobile Android (1) Linux Download (2) Marketing (5) Mobile (3) Mobile Courses (4) Mobile Marketing (4) MoneyGram (1) News (721) Node.js (5) Open Source (1) Photoshop (1) Protect Computer (1) Python (33) Python BeautifulSoup (1) Python For Data Science (2) Python-Books (6) Python-DVD-Training (1) Python-Exercises (140) Python-Framework (1) Python-IDE (1) Python-Modules (1) Python-pdf (2) Python-pyQt (1) Référencement (2) Script PHP (2) Security (6) SEO (1) Snipping Tool: Faq (1) Social Networks (1) Source Code (1) Statistics With SPSS (2) Surveillance Software (1) Travail à domicile (6) Tutoriels php en vidéos (2) Tutoriels-MySql (6) tutoriels-php (19) Utilitaires (1) VPS (1) Web Hosting (1) Webcam (1) Webmarketing (11) Western Union (1) Windows 10 (1) Windows 7 (4) Windows 7 Faq (2) Windows 8 (1) Windows Accessories (1) Windows Download (8) Windows Drivers (1) Windows Fonts (1) Windows Power Shell (2) Windows Registry (2) Windows Security (18) Windows Software (2) Windows Spyware (2) Windows utilities (3) Windows Virus (2) Windows Vista (3) Windows Wireless (1) Windows xp (1) Wordpress (1)
 

Sample text

Sample Text

 
Blogger Templates