In Python, strings are a sequence of characters and are used to represent textual data. The built-in string type in Python is str
. Strings are often used for representing names, addresses, descriptions, and many other types of textual data. In this section, we will learn about various string operations in Python.
+
operator. This means that we can add two or more strings together to form a new string. For example:string1 = "Hello"
string2 = "World"
string3 = string1 + string2
print(string3)
This code will output HelloWorld
.
*
operator. This means that we can repeat a string multiple times to form a new string. For example:string = "Hello"
string_repeated = string * 3
print(string_repeated)
This code will output HelloHelloHello
.
string = "Hello"
first_character = string[0]
print(first_character)
This code will output H
.
string = "Hello"
sliced_string = string[1:4]
print(sliced_string)
This code will output ell
.
len()
: Returns the length of the string.str.upper()
: Returns the string in uppercase.str.lower()
: Returns the string in lowercase.str.replace()
: Replaces a portion of the string with another string.str.split()
: Splits the string into a list of substrings based on a specified separator.For example:
string = "Hello World"
length = len(string)
print(length)
uppercase = string.upper()
print(uppercase)
lowercase = string.lower()
print(lowercase)
replaced_string = string.replace("Hello", "Goodbye")
print(replaced_string)
split_string = string.split(" ")
print(split_string)
This code will output:
11
HELLO WORLD
hello world
Goodbye World
['Hello', 'World']
In conclusion, strings are a fundamental aspect of programming in Python, and there are many operations that can be performed on them. By understanding these operations, we can effectively manipulate and work with strings in our Python programs.