What is the Python Strings with exmple

python string

python strings In programming languages, a string data type is used to represent a text rather than numbers. It consists of characters, numbers, spaces or any special characters. For instance, the word “Car” and the phrase “I have a car” are both strings. Typically, strings are enclosed in single or double quotation marks to differentiate them from numbers or variable names.

Strings in Python 

In Python, formatting strings is one of the most repetitive tasks you have to face during development. As of version 3.6, f-string is the most unique and comprehensive Python syntax for string formatting. Python f-strings are more concise, more readable, easier to understand, less error-prone and they are faster than other ways of formatting.

Before start, the strings topic read also what is python?

The following program showcases the string data type. 

# This program looks at string functions 

str="Hello World"
 print(str) 

This program’s output will be as follows: 

Hello World 

Python String Operators 

There are various operators that can be used to work with strings in Python. An operator is a symbol that performs a specific operation. In this instance, the operation is performed on strings. Let’s look at the various string operators in more detail, along with a simple example for each.

 Python String Concatenation Operator (+) 

This operator can be used to concatenate strings. Let’s look at an example of this. 

The following program showcases the concatenation operator. 

# This program looks at string functions

 str1="Hello " 
 str2="World"
print(str1+str2)

 This program’s output will be as follows:

Hello World

Python string Repetition Operator (*) 

This operator creates multiple copies of a string. Let’s look at an example of this. 

The following program showcases the repetition operator.

 # This program looks at string functions 

 str1="Hello " 
 print(str1*3) 

This program’s output will be as follows: 

Hello Hello Hello 

Python string Slice Operator ([x])

 This operator will retrieve a specified character from a particular index in a string. In this syntax ‘x’ denotes the character position in the string, with zero being the first character. Let’s look at an example of this. 

String Hello
Index01234

The following program showcases the slice operator.

 # This program looks at string functions 

str1="Hello " 
print(str1[1]) 
print(str1[2])

This program’s output will be as follows:

 e 
 l

Python string Range Slice Operator ([x:y]) 

This operator will retrieve a specified range of characters from a particular index in a string. In this syntax ‘x’ denotes the first character (which will be included) and ‘y’ denotes the last character (which will be excluded) of the string to be retrieved. When referring to the target string, the first character will be zero. 

String Hello
Index01234

This program shows how to use the range slice operator. 

 # This program looks at string functions 

str1="Hello " 
print(str1[1]) 
print(str1[2])

This program’s output will be as follows:

 El

Python string In Operator (in) 

This operator searches for a specified character in a target string. If the character exists in the string a value of ‘True’ is returned, else it returns ‘False’. Let’s look at an example of this. 

The program below showcases the ‘in’ operator.

# this program looks at string functions

str1="Hello"
print('e' in star1)
print('a' in star1)

This program’s output will be as follows:

True
False

Python string Not In Operator (not in) 

This operator does the opposite of the ‘in’ operator. It searches for a specified character in a target string. But if the character does not exist in the string a value of ‘True’ is returned, else it returns ‘False’. Let’s look at an example of this. 

The following program showcases the ‘not in’ operator. 

# This program looks at string functions

 str1="Hello " 
print('a' not in str1)
print('e' not in str1) 

This program’s output will be as follows:

True
False 

Python String Functions

 There are a variety of built-in functions available in Python to work with strings. A built-in function makes programming considerably easier by providing functionality, without the need to create it from scratch. Let’s look at these functions in more detail. 

String Functions

FunctionDescription
capitalize() This capitalizes the first letter of the string
center(width,char) This returns a string that is at least the specified width, created by padding the string with the character
count(str) This returns the number of times a string is contained in another string
find(str)This returns the index number of the substring in a string
isalpha()This checks if all characters of a string are alphabetic
characters isdigit()This checks if a string contains only digits
islower()This checks if a string contains all lower case characters
isupper()This checks if a string contains all upper case characters
len()This returns the length of the string
lower()This returns the string in lower case
upper()This returns the string in upper case
replace()This replaces a string with a new string
split()This splits a string based on the split character

Python string Capitalize Function 

This function is used to capitalize the first letter of a string.

syntax of capitalize()

string_name.capitalize() 

capitalize() Parameter

The capitalize() function does not takes any parameter.

Return value

The capitalize() function returns a string with the first character in the capital.

Let’s look at an example of this function. 

The following program showcases the capitalize function.

 # This program looks at string functions

 str1="hello " 
 print(str1.capitalize())

 ​This program’s output will be as follows:

Hello

Python string Center Function

This function returns a string that is centered in new string. Additional space is padded with a specified fill character. The syntax for this function is:

center(string width,fill character)

Let’s look at an example of this function.

The program below shows how to use the center function.

 # This program looks at string functions

 str1="hello" 
 print(str1.center(10,'1')) 

This program’s output will be as follows: 

11hello111

Python string Count Function 

This function returns the number of times a string is contained in another string. Let’s look at an example of this function. 

This program shows how to use the count function.

 # This program looks at string functions 

  str1="Hello Hello World" 
  print(str1.count("Hello")) 

This program’s output will be as follows:

2

Python string Find Function 

This function searches for and returns the index number of a specified string in another string. It will return the first position of the first character of the specified string. Let’s look at an example of this function.

 The following program showcases the find function.

# This program looks at string functions 

str1="Hello Hello World" 
print(str1.find("Hello"))

This program’s output will be as follows:

0

Python string Isalpha Function 

This function checks whether all characters in a string are alphabetic characters only. It will return ‘True’ if they are, else it will return ‘False’. Let’s look at an example of this function. 

The program below showcases the isalpha function.

# This program looks at string functions 
str1="Hello" 
print(str1.isalpha()) 

This program’s output will be as follows:

True

Python string  Isdigit Function 

This function checks whether all characters in a string are digit characters only. It will return ‘True’ if they are, else it will return ‘False’. Let’s look at an example of this function.

 This program shows how the isdigit function works.

 # This program looks at string functions
 str1="1" 
print(str1.isdigit()) 

This program’s output will be as follows:

True

Python string Islower Function 

This function checks whether all letters in a string are lowercase. It will return ‘True’ if they are, else it will return ‘False’. Let’s look at an example of this function.

 The following program is used to showcase the islower function.

 # This program looks at string functions 
 str1="hello"
 print(str1.islower())

 This program’s output will be as follows:

True

Python string Isupper Function

 This function checks whether all letters in a string are uppercase. It will return ‘True’ if they are, else it will return ‘False’. Let’s look at an example of this function. 

The next program showcases the isupper function.

# This program looks at string functions 
 str1="HELLO"
 print(str1.isupper()) 

This program’s output will be as follows: 


True

 Python string Len Function

 This function returns the length of a string. Let’s look at an example of this function. The following program shows how to use the len function.

# This program looks at string functions 
str1="hello" 
print(len(str1))

 This program’s output will be as follows:

5

Python string Lower Function 

This function returns the string in lowercase form. Let’s look at an example of this function. 

The program below showcases the lower function.

 # This program looks at string functions
 str1="HELLO" 
print(str1.lower())

This program’s output will be as follows:

hello

Python string Upper Function

 This function returns the string in uppercase form. Let’s now look at an example of this function. The following program shows how the upper function works.

 # This program looks at string functions
 str1="hello"
 print(str1.upper()) 

This program’s output will be as follows:

HELLO

Python string Replace Function 

This function replaces a specified string with a new string, in the original string. The syntax for this function is:

 replace(old string,new string,number of replacements)

The number of replacements is optional, if we wished to limit how many strings are to be replaced. Let’s now look at an example of this function. 

This program showcases the replace function.

# This program looks at string functions
 str1="hello new" 
print(str1.replace("new","world")) 

This program’s output will be as follows:

 hello world 

Python string Split Function 

This function splits a string based on a specified split character. It will then return a delimited list of strings. Let’s look at an example of this function. 

The following program is used to showcase the split function.

 # This program looks at string functions 
 str1="hello hello hello"
 print(str1.split(" ")) 

​This program’s output will be as follows:

['hello', 'hello', 'hello']

Exercise

Write a Python program to calculate the length of a string.

Sample Code

 def string_length(str1): 
     count = 0
     for char in str1: 
        count += 1
return count
print(string_length('Python Crash Course')) 

Exercise 2

Write a Python function that takes a list of words and returns the length of the longest one.

Sample code: 

def find_longest_word(words_list): 
 word_len = []
 for n in words_list:
  word_len.append((len(n), n)) 
word_len.sort() 
return word_len[-1][1] 
print(find_longest_word(["PHP", "Exercises", "Backend"])) 

Exercise 3:

Write a Python program to find the first appearance of the substring ‘not’ and ‘poor’ from a given string, if ‘not’ follows the ‘poor’, replace the whole ‘not’…’poor’ substring with ‘good’. Return the resulting string.

 Sample String : ‘The lyrics is not that poor!’ 

‘The lyrics is poor!’ 

Expected Result : ‘The lyrics is good!’ 

‘The lyrics is poor!’ 

Sample code:

def not_poor(str1): 
snot = str1.find('not') 
spoor = str1.find('poor') 
if spoor > snot and snot>0 and spoor>0: 
str1 = str1.replace(str1[snot:(spoor+4)], 'good')
 return str1 
Else:
 return str1 
print(not_poor('The lyrics is not that poor!'))
print(not_poor('The lyrics is poor!'))

Exercise 4: 

Write a Python script that takes input from the user and displays that input back in upper and lower cases.

 Sample code:

 user_input = input("What's your favourite language? ")
 print("My favourite language is ", user_input.upper()) 
 print("My favourite language is ", user_input.lower()) 

Exercise 5:

Write a Python function to get a string made of 4 copies of the last two characters of a specified string (length must be at least 2). 

Sample function and result : 

insert_end(‘Python’) -> onononon 

insert_end(‘Exercises’) -> eseseses 

Sample code:

 def insert_end(str): ​
         sub_str = str[-2:]
 ​        return sub_str * 4 
print(insert_end('Python')) 
print(insert_end('Exercises')) 

Exercise 6:

 Write a Python function to convert a given string to all uppercase if it contains at least 2 uppercase characters in the first 4 characters. 

Sample code:

def to_uppercase(str1): 
num_upper = 0 
for letter in str1[:4]: 
if letter.upper() == letter: 
num_upper += 1 
if num_upper >= 2: 
return str1.upper() 
return str1 
print(to_uppercase('Python'))
print(to_uppercase('PyThon'))

 Exercise 7:

Write a Python program to remove the characters which have odd index values of a given string. 

Sample code: 

def odd_values_string(str): 
result = "" 
for i in range(len(str)): 
if i % 2 == 0:
 result = result + str[i] 
return result 
print(odd_values_string('abcdef'))
 print(odd_values_string('pythoncrashcourse')) 

Exercise 8: 

Write a Python program that accepts a comma separated sequence of words as input and prints the unique words in sorted form (alphanumerically). 

Sample Words : red, white, black, red, green, black 

Expected Result : black, green, red, white,red

Sample code: 

items = input("Input comma separated sequence of words")
 words = [word for word in items.split(",")] 
print(",".join(sorted(list(set(words))))) 

Exercise 9:

Write a Python program to count repeated characters in a string. 

Sample        string:        ‘thequickbrownfoxjumpsoverthelazydog’ Expected output : 

o 4 

e 3 

u 2 

h 2 

r 2 

t 2 

Sample Code

import collections
 str1 = 'thequickbrownfoxjumpsoverthelazydog' 
d = collections.defaultdict(int)
 for c in str1:
 d[c] += 1 
for c in sorted(d, key=d.get, reverse=True): 
if d[c] > 1: 
print('%s %d' % (c, d[c]))