Codementor Events

Strings in Python

Published Dec 27, 2018Last updated Jan 20, 2020
Strings in Python

Introduction

  • Strings are arrays of characters & elements of an array that can be accessed using "indexing" and we can access a range of characters using "slicing"
  • Indices start with 0 from left side and -1 from right side
    string.png
  • In this a group of characters enclosed with in a single quote('hi'), double quotes("hi"), triple quotes('''hi''')

* Strings in python are arrays of bytes representing unicode characters

#single quote 
str = 'Hi'
print(str)

**Output: Hi**

#double quotes
str = "Hi"
print(str)

**Output: Hi**

#triple quotes
str = '''Hi
   welcome'''
print(str)

**Output: 
Hi
welcome**

Access Characters from the string

As i already said we can access individual characters using indexing and group of characters using slicing

s = 'codementor'
print(s[0])
print(s[1])
print(s[-1])
print(s[:])
print(s[2:5])
print(s[:5])
print(s[-6:])

Output:
c
o
r
codementor
dem
codem
mentor

if we are trying to access a character out of index it will give an Index error.

s = 'codementor'
print(s[10])
Output:
IndexError: string index out of range

String Methods

Python's built-in string methods are incredibly powerful. As the name implies, each of the following methods are available through class string.

Every string object is an instance of that class and has these methods available

1. str.capitalize()
Returns a copy of the string with its first character capitalized and the rest lowercased.
Example:

a="welcome to codementor"
print(a.capitalize())

Output:
Welcome to codementor

2. str.upper()
Returns a copy of string with all capital letters.
Example:

a="python"
print(a.upper())

Output: PYTHON

3. str.lower()
Returns a copy of string with all small letters.
Example:

a="Python"
print(a.lower())

Output: python

4. str.count(sub[, start[, end]])
Returns the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in string slice notation.
Example:

a="i love python and i love codementor"
print (a.count("love"))

Output: 2

5. str.index()
Returns the lowest index in the string where substring sub is found.

Example:

a="i love python and i love codementer"
print (a.index("o"))

Output: 3

6. str.find()
Returns the lowest index in the string where substring sub is found, Return -1 if sub is not found.
Example:

a="i love python and i love codementer"
print (a.index("o"))

Output: 3

7. str.endswith(suffix[, start[, end]])
Returns True if the string ends with the specified suffix, otherwise return False.
suffix can also be a tuple of suffixes to look for.With optional start, test beginning at that position. With optional end, stop comparing at that position.
Example 1:

a="String string String string String"
print (a.endswith("String"))
Output: True

8. str.isalnum()
Returns true if all characters in the string are alphanumeric and there is at least one character, false otherwise.
Example:

a="String string String string String3"
b="StringstringStringstringString3"
print (a.isalnum())
print (b.isalnum())

Output:
False
True

9. str.isalpha()
Returns true if all characters in the string are alphabetic and there is at least one character, false otherwise.
Example:

a="StringstringStringstringString3"
b="StringstringStringstringString"
print (a.isalpha())
print (b.isalpha())

Output:
False
True

10. str.isdigit()
Returns true if all characters in the string are digits and there is at least one character, false otherwise.
Example:

a="StringstringStringstringString3"
b="33434"
print (a.isdigit())
print (b.isdigit())

Output:
False
True

11. str.title()
Returns a titlecased version of the string(Camel Case) where words start with an uppercase character and the remaining characters are lowercase.
Example:

a="i love codementor"
print (a.title())

Output:
I Love Codementor

12. str.islower()
Returns true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.
Example:

a="I love codementor"
print (a.islower())

Output: False

13. str.isspace()
Returns true if there are only whitespace characters in the string and there is at least one character, false otherwise.
Example:

b="  "
print (b.isspace())

Output: True

14. str.istitle()
Returns true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise.
Example:

a="I love python"
print (a.istitle())

Output: False

15. str.isupper()
Returns true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise.
Example:

a="i love python"
print (a.isupper())

Output: False

16. str.replace(old, new[, count])
Returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Example:

a="sadhana loves python"
print (a.replace("sadhana","manaswi"))
print(a.replace("p","j"))

Output:
manaswi loves python
sadhana loves jython

17. str.split()
split() method splits the strings into sub strings. this will give output as list format

a = "Hello, python"
print(a.split(","))
Output: ['Hello', ' python']

18. str.startswith(prefix[, start[, end]])
Returns True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.
Example 1:

a="String string String string String"
print (a.startswith("String"))

Output: True

19. str.swapcase()
Returns a copy of the string with uppercase characters converted to lowercase and vice versa.
Example:

a="string String string string"
print (a.swapcase())

Output:
STRING sTRING STRING STRING

20. str.strip()
strip() Returns a copy of the string with the leading and trailing characters removed.
lstrip() removes all leading white spaces
rstrip() removes all trailing white spaces

a = " Hello, Python "
print(a.strip())
print(a.rstrip())
print(a.lstrip())
Output:
Hello, Python!
 Hello, Python!
Hello, Python!

21. str.len()
len() method returns the length of a string including white space

a = "Hello, Codementor"
print(len(a))
Output: 17

22. str.join()
join() method takes all items in an iterable and joins them in to one string.

s = ("Python", "love", "codementor")
x = " ".join(s)
print(x)

Output: Python love codementor

print("Sravan is a {0} boy, Also he is {0} student.So he {1}".format("very good","rocks"))t()**
format() inserts values in the string like format specifier
replacement fields delimited by { }

print("Sravan is a{0}boy, Also he is{0}student.So he{1}".format("very good","rocks"))
Output:
Sravan is a very good boy, Also he is very good student.So he rocks

Concatenation

  • We can perforn concatenation on the strings using "+" operator
s1 = "hi"
s2 = "Python"
s3 = s1 + s2
print(s3)

**Output: hiPython**
  • we can use * operator to repeat the string
s = "hi "
print(s * 3)

**Output: hi hi hi**

Looping over String

We can iterate over the string using forloop().
This example will give how many times a character occurred in the string

count = 0
for character in 'Welcome to codementor':
    if(character == 'o'):
        count += 1
print(count)

**Output: 4**

Membership using strings

Using this we can test if a substring exists in the given string or not, If exists it will give True otherwise it will give False

print('a' in 'python')
**Output: False**
print('a' not in 'python')
**Output: True**

This is all about strings. If you are having any questions regarding strings kindly comment.

Discover and read more posts from Sadhana Reddy
get started
post commentsBe the first to share your opinion
Show more replies