Strings and String Operations in Python
What are the strings ?
In Python, strings are sequences of characters that can be used to store
and manipulate text. They are commonly used to represent words, sentences
and other pieces of text in a program. Python strings is a collection of
Unicode characters.
String properties
Python strings can be enclosed in single, double or triple quotes.
print('Hello World')
print("Hello World")
print('''Hello World''')
print("""Hello World""")
//Output
Hello World
Hello World
Hello World
Hello World
Python strings are immutable
An object whose internal state can be changed is mutable. On the other
hand, immutable doesn't allow any change in the object once it has been
created. So the strings are immutable in Python they doesn't allow any
change in the object.
Example :
x = "Hello World"
x = "Hello"
x[0] = M
print(x)
//Output
TypeError: 'str' object does not support item assignment
String concatenation
Strings can be concatenated using + operator, by using this operator we
can able to concate two or more strings, words, and characters.
Example :
first_name = "Elon"
last_name = "-Musk"
full_name = first_name + last_name
print(full_name)
//Output
Elon-Musk
String slicing
In Python, string slicing is a way to extract a portion of a string by
specifying the start and end index of the characters you want to
extract.
Syntax :
string[start: end: step]
Where "string" is the name of the string variable, "start" is the index of the first character to include in the slice, and "end" is the index of the first character to exclude from the slice.
In Python, strings can be indexed using either positive or negative
numbers.
A positive index refers to the position of an element in a string,
starting from 0 for the first character.
From the first table the string "ASTRING" has a 'A' at index 0, 'S'
at index 1, and so on.
A negative index refers to the position of an element in a string,
starting from -1 for the last character.
From the second table the string "ASTRING" has a 'G' at index -1, 'N' at
index -2, and so on.
String slicing is a way to extract a portion of a string by specifying a
start and end index.
Here, are some examples of string slicing in Python
1. Extracting a single character :
string = "hello"
char = string[1]
print(char)
//Output
"e"
2. Extracting a substring :
string = "hello world"
substring = string[7:12]
print(substring)
//Output
"world"
3. Extracting a substring from the end of the string :
string = "hello world"
substring = string[-6:]
print(substring)
//Output
"world"
4. Extracting a substring from the start of the string :
string = "hello world"
substring = string[:5]
print(substring)
//Output
"hello
5. Extracting every nth character :
string = "hello world"
substring = string[::2]
print(substring)
//Output
"hlowrd"
6. Extracting a substring in reverse order :
string = "hello world"
substring = string[::-1]
print(substring)
//Output
"dlrow olleh"
7. Extracting a substring using both positive and negative indexing :
string = "hello world"
substring = string[-6:5]
print(substring)
//Output
"wor"
Strings Methods
In Python, strings have several built-in methods that can be used to
perform various operations on them.
Methods | Description |
---|---|
capitalize() | Converts the first character to upper case |
casefold() | Converts string into lower case |
center() | Returns a centered string |
count() | Returns the number of times a specified value occurs in a string |
encode() | Returns an encoded version of the string |
endswith() | Returns true if the string ends with the specified value |
expandtabs() | Sets the tab size of the string |
find() | Searches the string for a specified value and returns the position of where it was found |
format() | Formats specified values in a string |
format_map() | Formats specified values in a string |
index() | Searches the string for a specified value and returns the position of where it was found |
isalnum() | Returns True if all characters in the string are alphanumeric |
isalpha() | Returns True if all characters in the string are in the alphabet |
isascii() | Returns True if all characters in the string are ascii characters |
isdecimal() | Returns True if all characters in the string are decimals |
isdigit() | Returns True if all characters in the string are digits |
isidentifier() | Returns True if the string is an identifier |
islower() | Returns True if all characters in the string are lower case |
isnumeric() | Returns True if all characters in the string are numeric |
isprintable() | Returns True if all characters in the string are printable |
isspace() | Returns True if all characters in the string are whitespaces |
istitle() | Returns True if the string follows the rules of a title |
isupper() | Returns True if all characters in the string are upper case |
join() | Converts the elements of an iterable into a string |
ljust() | Returns a left justified version of the string |
lower() | Converts a string into lower case |
lstrip() | Returns a left trim version of the string |
maketrans() | Returns a translation table to be used in translations |
partition() | Returns a tuple where the string is parted into three parts |
replace() | Returns a string where a specified value is replaced with a specified value |
rfind() | Searches the string for a specified value and returns the last position of where it was found |
rindex() | Searches the string for a specified value and returns the last position of where it was found |
rjust() | Returns a right justified version of the string |
rpartition() | Returns a tuple where the string is parted into three parts |
rsplit() | Splits the string at the specified separator, and returns a list |
rstrip() | Returns a right trim version of the string |
split() | Splits the string at the specified separator, and returns a list |
splitlines() | Splits the string at line breaks and returns a list |
startswith() | Returns true if the string starts with the specified value |
strip() | Returns a trimmed version of the string |
swapcase() | Swaps cases, lower case becomes upper case and vice versa |
title() | Converts the first character of each word to upper case |
translate() | Returns a translated string |
upper() | Converts a string into upper case |
zfill() | Fills the string with a specified number of 0 values at the beginning |
Escape sequences
In Python, an escape sequence is a combination of characters that represents a special character. Escape sequences are used to represent characters that are not easily entered into a string, such as newline, tab, or quotes.
Here, are some examples of commonly used escape sequences
1) \n : represents a newline character. It is used to insert a new line in a string.
string = "Hello\nWorld"
print(string)
//Output:
Hello
World
2) \t : represents a tab character. It is used to insert a tab space in a string.
string = "Hello\tWorld"
print(string)
//Output:
Hello World
3) \" : represents a double quote character. It is used to include a double quote within a string that is enclosed in double quotes.
string = "He said, \"Hello World\""
print(string)
//Output:
He said, "Hello World"
4) \\ : represents a backslash. It is used to include a backslash within a string.
string = "Hello\\World"
print(string)
//Output:
Hello\World
5) /r : represents a Carriage return. It is used to move the cursor to the beginning of the current line.
string = "Hello\rWorld"
print(string)
//Output:
WorldolleH
These are just a few examples of escape sequences in Python. There are other escape sequences available as well, such as '\a','\b','\f','\v', etc. Each escape sequence has a specific use case, and it's good to familiarize yourself with them to be able to use the appropriate one for a specific task.
0 Comments
Please do not add Any Spam link in Comments !