You must have heard about "String". This string is not exactly the string of guitar or some other string. In program when we refer to a sentence of a series of words which is assigned to a variable that is called a string.
Example. var_text = "Hello people this is python blog."
So I hope you get the idea what string looks like.
Now lets get on with the coding:-
1) Creating strings in python
1 2 3 4 5 6 | >>> #_1 creating strings in python >>> a = 'python' >>> b = 'blog' >>> c = 'tutorial' >>> d = 'is' >>> e = 'awesome' |
2) View output with print( ) statement
1 2 3 4 5 6 7 8 9 10 11 | >>> #_2 view output with print() statement >>> print(a) python >>> print(b) blog >>> print(c) tutorial >>> print(d) is >>> print(e) awesome |
3) View output in single line
1 2 3 4 5 6 7 8 9 10 | >>> #_3 view output in single line >>> # manipulate strings using + >>> print(a+b) pythonblog >>> print(a+b+c+d+e) pythonblogtutorialisawesome >>> print(a+' '+b+' '+c+' '+d+' '+e) python blog tutorial is awesome |
4) View output using \n in single line
1 2 3 4 5 6 7 | >>> #_4 view output using \n in single line >>> print(a+'\n'+b+'\n'+c+'\n'+d+'\n'+e) python blog tutorial is awesome |
5) String indexing and manipulating (subscript notation)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>> #_5 string indexing and manipulating (subscript notation) >>> # string index starts from 0 >>> print(a[0]) p >>> print(b[1]) l >>> print(c[2]) t >>> print(d[3]) Traceback (most recent call last): File "<pyshell#75>", line 1, in <module> print(d[3]) IndexError: string index out of range >>> #reason variable 'd' has only two letters that is 0,1 there is no 2,3... |
6) Manipulating string
1 2 3 | >>> #_6 manipulating string >>> print(a[0]+b[1]+e[0]+a[5]+e[2]+c[0]) planet |
7) Slicing string
1 2 3 4 5 6 7 8 | >>> #_7 slicing string >>> print(a[0:2]) py >>> print(b[1:3]) lo >>> print(c[::2]) ttra >>> |
8) Negative index slicing string
1 2 3 4 5 6 7 | >>> #_8 negative index slicing string >>> print(a[-7:-4]) py >>> print(b[-6:-3]) b >>> print(c[-1::-1]) lairotut |
9) String operator %
1 2 3 4 5 6 | >>> #_9 string operator % >>> print(' %(placeholder)s'%{"placeholder":"XXXX"}) XXXX >>> print(' %(placeholder)s'%{"placeholder":"XXXX, YYYY, ZZZZ"}) XXXX, YYYY, ZZZZ >>> |
10) String operator % using integer
1 2 3 4 5 6 7 8 | >>> #_10 string operator % using integer >>> print(' %(integer)01d'%{"integer":1}) 1 >>> print(' %(integer)02d'%{"integer":1}) 01 >>> print(' %(integer)03d'%{"integer":1}) 001 >>> |
11) Using string operator % for text placeholder and integer
1 2 3 | >>> #_11 using string operator % for text placeholder and integer >>> print( '%(a)s %(n)03d - program is the best.'%{"a":"Python","n":3}) Python 003 - program is the best. |
12) Using \n in the above code
1 2 3 4 | >>> #_12 using \n in the above code >>> print(' %(a)s %(n)03d - program is the best \n %(a)s helped me understand programming.'%{"a":"Python","n":3}) Python 003 - program is the best Python helped me understand programming. |
13) Multiple place holders in single string
1 2 3 4 5 6 | >>> #_13 multiple place holders in single string >>> print(' I love %(a)s. \n I like %(b)s. \n I like to %(c)s. \n my %(d)s is %(num)03d.'%{"a":"to code","b":"ice-cream","c":"travel","d":"age","num":32}) I love to code. I like ice-cream. I like to travel. my age is 032. |
14) Other ways of using %
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | >>> #_14 other ways of using % >>> print('Hello everyone I am using Python %d.7 version.' % 3.7) Hello everyone I am using Python 3.7 version. >>> print('%s %s %d %d %f %f' % ('Hercules', 'Zeus', 100, 20, 3.2, 1)) Hercules Zeus 100 20 3.200000 1.000000 >>> print('This is a +%d integer' % 10) This is a +10 integer >>> print('This is a negative -%d integer' % 250) This is a negative -250 integer >>> print('This is a confused -%d integer' % 300) This is a confused -300 integer |
15) Manipulate string to integer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | >>> #_15 manipulate string to integer >>> d = '365' >>> print(10 * int(d)) 3650 >>> print(a * 5) hellohellohellohellohello >>> >>> print('7' + '4') 74 >>> # string + integer is not allowed >>> print('7' + 4) Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> print('7' + 4) TypeError: can only concatenate str (not "int") to str >>> print(float('7') + float('4')) 11.0 |
16) Common methods for string class
1 2 3 4 5 | >>> #_16 common methods for string class >>> #counting letter 'o' >>> text = "It is so simple to be happy but it is so difficult to be simple" >>> print(text.count('o')) 4 |
17) Upper case
1 2 3 | >>> #_17 upper case >>> print(text.upper()) IT IS SO SIMPLE TO BE HAPPY BUT IT IS SO DIFFICULT TO BE SIMPLE |
18) Lower case
1 2 3 | >>> #_18 lower case >>> print(text.lower()) it is so simple to be happy but it is so difficult to be simple |
19) Join text with space ' '
1 2 3 | >>> #_19 join text with space ' ' >>> print(' '.join(text)) I t i s s o s i m p l e t o b e h a p p y b u t i t i s s o d i f f i c u l t t o b e s i m p l e |
20) Split text where ever space ' ' is present
1 2 3 4 | >>> #_20 split text where ever space ' ' is present >>> print(text.split(' ')) ['It', 'is', 'so', 'simple', 'to', 'be', 'happy', 'but', 'it', 'is', 'so', 'difficult', 'to', 'be', 'simple'] >>> |
21) If text is uppercase then true else false
1 2 3 4 5 6 | >>> #_21 if text is uppercase then true else false >>> up_text = text.upper() >>> up_text 'IT IS SO SIMPLE TO BE HAPPY BUT IT IS SO DIFFICULT TO BE SIMPLE' >>> print(up_text.isupper()) True |
22) Check if lower case then true else false
1 2 3 4 | >>> #_22 check if lower case then true else false >>> print(up_text.islower()) False >>> |
23) If all characters are alpha-numeric
1 2 3 4 | >>> #_23 if all characters are alpha-numeric >>> #contains both letters and numbers >>> print(text.isalnum()) False |
24) Contains both letters and numbers
1 2 3 4 5 | >>> #_24 contains both letters and numbers >>> new_text = "H2SO4" >>> print(new_text.isalnum()) True >>> |
25) Character count
1 2 3 | >>> #_25 character count >>> print(len(text)) 63 |
26) Converts character to decimal
1 2 3 4 5 6 7 8 9 10 | >>> #_26 converts character to decimal >>> print(ord('A')) 65 >>> print(ord('B')) 66 >>> print(ord('a')) 97 >>> print(ord('b')) 98 >>> |
27) Converts decimal back to character
1 2 3 4 5 6 7 8 9 10 | >>> #_27 converts decimal back to character >>> print(chr(65)) A >>> print(chr(42)) * >>> print(chr(118)) v >>> print(chr(60)) < >>> |
28) Using Quote
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | >>> #_28 using quote >>> # the backslash is needed to escape the apostrophe. >>> print('What\'s up?') What's up? >>> # the apostrophe is not needed in this case. >>> print("What's up?") What's up? >>> # the apostrophe is needed to add on the quotes to the text >>> print("\"What's up?\"") "What's up?" >>> # triple quotes can escape single, double, and a lot more. >>> print("""What's up? Does the "" need an escape?""") What's up? Does the "" need an escape? |
29) Formatting strings using commas
1 2 3 | >>> #_29 formatting strings using commas >>> print('Mixing numbers like ', 8, 'with text') Mixing numbers like 8 with text |
30) The format string syntax was introduced in python3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | >>> #_30 The format string syntax was introduced in python3 >>> source:- https://docs.python.org/3/library/string.html#formatstrings >>> var_1 = 'test' >>> var_2, var_3 = 'move it move it', 'MOVE IT!' >>> dog = 'Lassie' >>> print('This is a {}'.format(var_1)) This is a test >>> print('I like to {}, you like to {}!'.format(var_2, var_3)) I like to move it move it, you like to MOVE IT!! >>> print('This is {}, and this is B'.format('A', 'B')) This is A, and this is B >>> print('Number {1} and number {0}'.format(100, 200)) # keyword position Number 200 and number 100 |
31) Accessing arguments by name
1 2 3 4 5 6 7 | >>> #_31 accessing arguments by name >>> print('Mount Whitney is located at {latitude}°N, and {longitude}°W'.format(latitude='35.5785', longitude='118.2923')) Mount Whitney is located at 35.5785°N, and 118.2923°W >>> temp = {'day_one': 90, 'day_two': 100} >>> print('It is {day_one}° F today and tomorrow it will be {day_two}° F'.format(**temp)) It is 90° F today and tomorrow it will be 100° F |
32) Accessing arguments items
1 2 3 4 | >>> #_32 accessing arguments' items: >>> point = (5, 10) >>> print('The point values are {0[0]} and {0[1]}'.format(point)) The point values are 5 and 10 |
33) Iterating with a for loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | >>> #_33 iterating with a for loop >>> text = 'what a wonderful world' >>> for letter in text: print(letter) w h a t a w o n d e r f u l w o r l d >>> |
34) Iterating with a while loop
1 2 3 4 5 | >>> #_34 iterating with a while loop >>> # this will create non-stop loop >>> i = 0 >>> while i < len(text): print(text[i]) |
35) Prints the content in triple quotes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | >>> #_35 prints the content in triple quotes >>> def triple_quote_docs(): """ In the golden lightning Of the sunken sun, O'er which clouds are bright'ning, Thou dost float and run, Like an unbodied joy whose race is just begun. """ return >>> print(triple_quote_docs.__doc__) In the golden lightning Of the sunken sun, O'er which clouds are bright'ning, Thou dost float and run, Like an unbodied joy whose race is just begun. >>> |
36) Accessing an argument's attributes
1 2 3 4 5 6 7 8 9 10 11 12 | >>> #_36 accessing an argument's attributes >>> class Rectangle: def __init__(self, length, width): self.length = length self.width = width def __str__(self): return 'Rectangle({self.length}, {self.width})'.format(self=self) >>> rect = Rectangle(10, 5.5) >>> print(rect.__str__()) Rectangle(10, 5.5) |
37) Aligning text
1 2 3 4 5 6 7 8 9 10 11 12 | >>> #_37 Aligning text >>> print('{:<10}'.format('X')) # left align X >>> print('{:>10}'.format('X')) # right align X >>> print('{:^10}'.format('X')) # center X >>> print('{:?^10}'.format('X')) # add a fill character ????X????? |
38) Formatting Binary, Octal, and Hexadecimals
1 2 3 4 5 6 7 8 9 | >>> #_38 formatting binary, octal, and hexadecimals >>> print('Binary number: {0:b}'.format(50)) Binary number: 110010 >>> print('Octal number: {0:o}'.format(100)) Octal number: 144 >>> print('Hexadecimal number: {0:x}'.format(2555)) Hexadecimal number: 9fb |
39) Using commas as a delimiter
1 2 3 4 5 6 | >>> #_39 using commas as a delimiter >>> print('{:,}'.format(2783727282727)) 2,783,727,282,727 >>> print('{:.2%}'.format(90.60/100)) 90.60% |
40) Formatted string literals also known as f strings
1 2 3 4 5 6 7 8 9 10 11 12 | >>> #_40 formatted string literals also known as f strings >>> # source - https://docs.python.org/3/reference/lexical_analysis.html#f-strings >>> item_1, item_2, item_3 = 'computer', 'mouse', 'browser' >>> print(f"He uses a {item_1}.") He uses a computer. >>> print(f"He uses a {item_2} and a {item_3}.") He uses a mouse and a browser. >>> print(f"He uses a {item_1} 3 times a day.") He uses a computer 3 times a day. |
40.1) Templates
1 2 3 4 5 6 7 | >>> #_40.1 Templates >>> # source - https://docs.python.org/3/library/string.html#template-strings >>> from string import Template >>> poem = Template('$x are red and $y are blue') >>> print(poem.substitute(x='roses', y='violets')) roses are red and violets are blue |
Hope you like the tutorial.
Python is simple and fun to play with and yet very powerful. 🔥