Table of contents
- What are strings?
- Why we have two ways of defining stringsđ€?
- Properties of Strings
- Indexing
- Immutability of Strings
- Concatenation
- String Methods
- - s.lower()
- - string_name.upper()
- - string_name.strip()
- string_name.isalpha()
- string_name.isdigit()
- string_name.isspace()
- string_name.startswith(âsub_stringâ)
- string_name.endswith(âsub_stringâ)
- string_name.find(sub_string)
- string_name.replace('old' , 'new')
- string_name.split('delim')
- string_name.join(list)
- Slicing
- Repeating string
- Various Print Formats
Namaste Coders!
In this article, we will discover the Strings in Pythonđ.
What are strings?
Anything written within single, double or triple quotes is a string.
So simple it is, isn't it đ?
Python has a built-in string class named âstrâ with many handy features (there is an older module named âstringâ which you should not use).
# strings in python
s1='python'
s2="programming"
Why we have two ways of defining stringsđ€?
This can be explained from following exampleđ
# If you want to use single quote as a part of string
s="Let's begin with Python"
# If you want to add double quotes as a part of string
s2='" Coding is about debugging "'
print(s)
print(s2)
Output
Let's begin with Python
" Coding is about debugging "
Properties of Strings
- Strings are iterable which means we can loop it.
- We can get individual element from a list by indexing.
- Strings are immutable that means you cannot change the strings once declared.
Escape characters can also be used inside strings by using slash.\n (for new line), \t (space ),\â(single quote),\b(back space)
# Using Escape sequence
s='let\'s\nbegin\tprogramming'
print(s)
# To use slash as a character and not escape sequence
s2=r'C:\newfolder'
print(s2)
Output
let's
begin programming
C:\newfolder
Indexing
Each item in a list corresponds to an index number, which is an integer value, starting with the index number 0.
Strings also follow negative indexing from right to left beginning from -1.
Negative Indexing
s="kiwi"
print("index 0: ",s[0]) # index 0: k
print("index 1: ",s[1]) # index 1: i
print("index 2: ",s[2]) # index 2: w
print("index 3: ",s[3]) index 3: i
# Reverse indexing
print("index -1: ",s[-1]) # index -1: i
print("index -2: ",s[-2]) # index -2: w
print("index -3: ",s[-3]) # index -3: i
print("index -4: ",s[-4]) # index -4: k
Immutability of Strings
Strings are immutable. Thus, we cannot change value in a string.
s="Python"
s[5]='@'
print(s)
It will through TypeError
Concatenation
In Python, (+) operator is used for joining two strings,It is called concatenation.
s1="python"
s2="programming"
print(s1+' '+s2) # python programming
String Methods
- s.lower()
returns the lowercase version of the string
s="Python PROGRAMMING"
print(s.lower())
# 'python programming'
- string_name.upper()
returns the uppercase version of the string
s="Python PROGRAMMING"
print(s.upper())
# 'PYTHON PROGRAMMING'
- string_name.strip()
returns a string with whitespace removed from the start and end.
s=' python '
print(s.strip())
# 'python'
string_name.isalpha()
tests if all the string chars are alphabets
s="python"
print(s.isalpha())
# True
s="python3"
print(s.isalpha())
# False
string_name.isdigit()
tests if all the string chars are digits.
s="python123"
print(s.isdigit())
# False
s="123"
print(s.isdigit())
# True
string_name.isspace()
tests if all the string chars are spaces.
s="123"
print(s.isspace())
# False
s=" "
print(s.isspace())
# True
string_name.startswith(âsub_stringâ)
returns True if the string starts with the given other string.
s="python programming"
print(s.startswith('o'))
# False
print(s.startswith('p'))
# True
string_name.endswith(âsub_stringâ)
returns True if the string endswith the given other string.
s="python programming"
print(s.endswith('o'))
# False
print(s.endswith('g'))
# True
string_name.find(sub_string)
searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found
s='python'
print(s.find('y'))
# 1
print(s.find('a'))
# -1
string_name.replace('old' , 'new')
returns a string where all occurrences of 'old string' have been replaced by 'new string'.
s="python"
print(s.replace('o','@'))
# 'pyth@n'
string_name.split('delim')
returns a list of substrings separated by the given delimiter. The delimiter is not a regular expression, itâs just text. âaaa,bbb,cccâ.split(â,â) -> [âaaaâ, âbbbâ, âcccâ]. As a convenient special case s.split() (with no arguments) splits all the values.
s="python programming is best"
print(s.split(" "))
# ['python', 'programming', 'is', 'best']
print(s.split(" ")[1])
# 'programming'
print(s.split( "p"))
#['', 'ython ', 'rogramming is best']
string_name.join(list)
opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. âââ.join([âramâ, âshamâ, âsamâ]) -> ramâshamâsam
s=["ram","sham","sam"]
print((',').join(s))
# 'ram,sham,sam'
print(('-').join(s))
# 'ram-sham-sam'
Slicing
Slicing is a very fun loving technique of lists. It allows us to fetch a part from string. One can use both negative and positive indexing in it.end_index is exclusive whereas start_index is inclusive.
syntax
string_name[start_index:end_index:space]
Example
s="python programming"
print(s[: :]) # python programming
print(s[:2]) # py
print(s[-5:-2]) # mmi
print(s[: : -1]) # gnimmargorp nohtyp
Repeating string
we can repeat a string as many time just by using * operator
s="python"*5
print(s)
# 'pythonpythonpythonpythonpython'
Various Print Formats
There are various print formats which makes printing strings very easy rather than using (+) operator again and again.
# classic approach
print(str(n1) + " + "+ str(n2) +" = "+str(ans)) #43 + 53 = 96
# using .format
# In it we have to provide placeholders where we can fill the values
print('{} + {} = {}'.format(n1,n2,ans)) #43 + 53 = 96
# using access specifier
# %d for integer %f for decimal point %s for string
print('%d + %d = %d'%(n1,n2,ans)) #43 + 53 = 96
# f-strings
# It is best approach as we specify variable names within print statement
# It avoids confusion as we do not need to maintain any tuple
print(f'{n1} + {n2} = {ans}') #43 + 53 = 96
The End
I hope you enjoyed the article and had a good learning experience.
Follow for more articles and keep sharingđ©
Keep coding