String Data Type in python

WHAT ARE STRINGS?

In Python, a string is a sequence of characters, enclosed in either single quotes (”) or double quotes (“”). Strings are immutable, which means once a string is created, its contents cannot be changed.

Here is an example of a string:

my_string = "Hello, World!"

You can access individual characters within a string using indexing. The index of the first character in a string is 0, and you can count backwards from the end of the string using negative indices. Here are some examples:

first_char = my_string[0]      # returns 'H'
last_char = my_string[-1]      # returns '!'

You can also slice a string to extract a substring. Slicing is done using the colon (:) operator. The syntax for slicing is [start_index:end_index], where start_index is the index of the first character you want to include in the substring, and end_index is the index of the first character you want to exclude from the substring. If you omit start_index, Python assumes you want to start at the beginning of the string, and if you omit end_index, Python assumes you want to go to the end of the string. Here are some examples:

substring = my_string[0:5]    # returns 'Hello'
substring2 = my_string[7:]    # returns 'World!'

You can also concatenate two or more strings using the + operator. Here is an example:

greeting = "Hello"
name = "Alice"
full_greeting = greeting + ", " + name + "!"

This would set full_greeting to "Hello, Alice!".

here are some more operations and methods you can perform on strings in Python:

  • len(string): returns the length of the string
my_string = "Hello, World!"
length = len(my_string)   # returns 13

 

string.upper(): returns a new string with all characters in uppercase

my_string = "Hello, World!"
uppercase_string = my_string.upper()   # returns "HELLO, WORLD!"

string.lower(): returns a new string with all characters in lowercase

my_string = "Hello, World!"
lowercase_string = my_string.lower()   # returns "hello, world!"

string.strip(): returns a new string with leading and trailing whitespace removed

my_string = "  Hello, World!  "
stripped_string = my_string.strip()   # returns "Hello, World!"

string.replace(old, new): returns a new string with all occurrences of old replaced by new

my_string = "Hello, World!"
new_string = my_string.replace("World", "Python")   # returns "Hello, Python!"

string.split(separator): returns a list of substrings, split by the specified separator (default is whitespace)

my_string = "Hello, World!"
words = my_string.split(",")   # returns ["Hello", " World!"]

string.join(iterable): returns a new string by concatenating the elements of an iterable, separated by the string

words = ["Hello", "World", "!"]
my_string = ", ".join(words)   # returns "Hello, World, !"

string.format(): allows you to insert values into a string using placeholders

name = "Alice"
age = 30
greeting = "Hello, my name is {} and I am {} years old.".format(name, age)

This would set greeting to "Hello, my name is Alice and I am 30 years old.". You can also use numbered placeholders to specify the order of the values in the format method, or use named placeholders to give them descriptive names.

Here are some additional operations and methods you can use with strings in Python:

  • string.startswith(prefix): returns True if the string starts with the specified prefix, False otherwise.
my_string = "Hello, World!"
starts_with_hello = my_string.startswith("Hello")   # returns True

string.endswith(suffix): returns True if the string ends with the specified suffix, False otherwise.

my_string = "Hello, World!"
ends_with_exclamation = my_string.endswith("!")   # returns True

string.find(substring): returns the index of the first occurrence of the specified substring in the string, or -1 if the substring is not found.

my_string = "Hello, World!"
index_of_world = my_string.find("World")   # returns 7

 

string.count(substring): returns the number of times the specified substring appears in the string.

my_string = "Hello, World!"
number_of_l = my_string.count("l")   # returns 3

 

string.isalpha(): returns True if all characters in the string are alphabetic, False otherwise.

my_string = "Hello, World!"
is_alpha = my_string.isalpha()   # returns False (because of the comma and the space)

string.isdigit(): returns True if all characters in the string are digits, False otherwise.

my_string = "12345"
is_digit = my_string.isdigit()   # returns True

 

string.islower(): returns True if all alphabetic characters in the string are lowercase, False otherwise.

my_string = "hello, world!"
is_lower = my_string.islower()   # returns True

string.isupper(): returns True if all alphabetic characters in the string are uppercase, False otherwise.

my_string = "HELLO, WORLD!"
is_upper = my_string.isupper()   # returns True

 

string.encode(): returns a bytes object encoding the string using the specified encoding (default is UTF-8)

my_string = "Hello, World!"
encoded_bytes = my_string.encode()   # returns b'Hello, World!'

 

string.center(width): returns a new string centered within a string of a specified width, with any extra space filled by a specified character (default is whitespace).

my_string = "Hello, World!"
centered_string = my_string.center(20, "*")   # returns "***Hello, World!***"

string.ljust(width): returns a new string left-justified within a string of a specified width, with any extra space filled by a specified character (default is whitespace).

my_string = "Hello, World!"
left_justified_string = my_string.ljust(20, "*")   # returns "Hello, World!*******"

string.rjust(width): returns a new string right-justified within a string of a specified width, with any extra space filled by a specified character (default is whitespace).

my_string = "Hello, World!"
right_justified_string = my_string.rjust(20, "*")   # returns "*******Hello, World!"

 

string.swapcase(): returns a new string with uppercase characters converted to lowercase and vice versa.

my_string = "Hello, World!"
swapped_case_string = my_string.swapcase()   # returns "hELLO, wORLD!"

 

string.title(): returns a new string with the first letter of each word capitalized.

my_string = "hello, world!"
title_string = my_string.title()   # returns "Hello, World!"

 

string.capitalize(): returns a new string with the first character capitalized and the rest in lowercase.

my_string = "hello, world!"
capitalized_string = my_string.capitalize()   # returns "Hello, world!"

 

Copywrite © 2020-2024, CBSE Python,
All Rights Reserved
error: Content is protected !!