Character strings are a type of composite data consisting exclusively of characters. They cannot be modified: you must create a new channel, and copy what you want to change.
They are defined with apostrophes, or quotation marks: 'aze' and "sqd" are two strings.
>>> chain = "Hello" >>> chain Hello >>> type(string) <type'str'>
We read a string with 'raw_input()', possibly passing the message to be displayed as an argument. The result is displayed with 'print()':
>>> chaine = raw_input() Coucou >>> print chaine Coucou >>> dd = 'CouCou' >>> 'ou' in dd True >>> chaine2 = raw_input("Your string: ") Your string: Coucou2 >>> print chaine2 Coucou2
We can quite easily place a \n in a string, in which case we will have the expected line break.
If toto is a string, toto[i] is the character i+1 of this string, and len(toto) its length. Finally, we can concatenate two strings with +, and also use * :
>>> toto = "abcde" >>> len(toto) 5 >>> toto[0] a >>> toto[1] b >>> toto[-1] e >>> toto + "fg" + "fg abcdefg >>> "fg"*3 fgfgfgfg
We convert the string s='123' into a number by int(s) (float, if it is a real one). Finally, the number N=123 is transformed into strings by str(N)...
>>> s = '123' >>> s, type(s) ('123', <type'str' >) >>> n = int(s) >>> n, type(n) (123, <type'int'>) >>> str(n), n ('123', 123)
The for loop can go through a string of characters. For example:
>>> for k in "letters": .... print k ... l e t t r e s
Each letter of the letters word is displayed, one per line.
In the same spirit, the condition of the if can relate to the membership of a character in a string:
>>> toto = 'aze' >>> if 'a' in toto: ... print toto ... aze
In the above, the condition is verified, so 'aze' is displayed. We can use "not in" instead of "in" if necessary.
In the two previous methods, one can replace "l" by "r", to perform the actions not on the left, but on the right.
Let's illustrate some of the previous methods:
>>> "abs".replace('s','c') "abc >>> "qAd".lstrip('A') "qAd >>> "qAd".lstrip('qA') 'd'
Let's illustrate the previous methods:
>>> "toto".endswith('o') True >>> "azea".islower() True
Other methods that can be applied to an object of the str class:
Let's illustrate the previous methods:
>>> "aze'.join('xwc') "xazewazec >>> "abs'.find('s') 2 >>>> "q d ez zzz".split(' ') ['q','d','ez','zzz']
Encrypt/decrypt a string of characters, using the so-called sawtooth transposition method: to encrypt the message
sawtooth transposition
we write it on two lines, just like a sawtooth:
t a s o i i n n a n d d s i d r n p s t o e d n s e c e
This gives, when we concatenate the two lines, the figure:
tasoiinnetdsirnpstoednsece
Two functions can be performed: one for encryption and the other for decryption.