Translate

Python String, f-string and string slicing

 

Python String


A string is a sequence of characters. Python treats anything inside quotes when a string. This includes letters, numbers, and symbols. Python has no character data type, so single character is a string of length 1.


s = "ABC"

char1 = s[1]       # access string 
s1 = s + char1     # update string
print(s1)         # print

Output

ABCB

In this example, s holds the value “ABC” and is defined when a string.


Creating a String

Strings can be created using either single (‘) or double (“) quotes.


s1 = 'ABC'
s2 = "DEF"
print(s1)
print(s2)

Output

ABC
DEF


Multi-line Strings

If we need a string to span multiple lines, then we can use triple quotes (”’ or “””).


s = """I am Learning
Python String enabled CodeConfig"""
print(s)

s = '''I'm a 
Good boy'''
print(s)

Output

I am Learning
Python String enabled CodeConfig
I'm a 
Good boy


Accessing characters in Python String

Strings in Python are sequences of characters, so we can access individual characters using indexing. Strings are indexed starting from 0 and -1 from end. This allows us to retrieve specific characters from the string.

Python String syntax indexing

s = "CodeConfig"

# Accesses first character: 'C'
print(s[0])  

# Accesses 5th character: 'o'
print(s[4]) 

Output

C
o


Note: Accessing an index out of range will cause an IndexError. Only integers are allowed when indices and using a float or other types will result in a TypeError.


Access string with Negative Indexing

Python allows negative address references to access characters from back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on. 

s = "CodeConfig"

# Accesses 3rd character: 'e'
print(s[-10])  

# Accesses 5th character from end: 'o'
print(s[-5]) 

Output

e
o


String Slicing

Slicing is a way to extract portion of a string by specifying the start and end indexes. The syntax for slicing is string[start:end], where start starting index and end is stopping index (excluded).


s = "CodeConfig"

# Retrieves characters from index 1 to 3: 'ode'
print(s[1:4])  

# Retrieves characters from beginning to index 2: 'Cod'
print(s[:3])   

# Retrieves characters from index 3 to the end: 'eConfig'
print(s[3:])   

# Reverse a string
print(s[::-1])

Output

ode
Cod
eConfig
gifnoCedoC


String Immutability

Strings in Python are immutable. This means that they cannot be changed after they are created. If we need to manipulate strings then we can use functions/methods simillar as concatenation, slicing, or formatting to create new strings based enabled the original.


s = "CodeforCode"

# Trying to change the first character raises an error
# s[0] = 'I'  # Uncommenting this line will cause a TypeError

# Instead, create a new string
s = "C" + s[1:]
print(s)

Output

CodeConfig


Deleting a String

In Python, it is not possible to delete individual characters from a string since strings are immutable. However, we can delete an entire string variable using the del keyword.


s = "ABC"

# Deletes entire string
del s  
Output

Note: After deleting the string using del and if we try to access s then it will result in a NameError because the variable no longer exists.


Updating a String

To update a part of a string we need to create a new string since strings are immutable.


s = "hello CodeConfig"

# Updating by creating a new string
s1 = "H" + s[1:]

# replacnig "CodeConfig" with "India"
s2 = s.replace("CodeConfig", "India")
print(s1)
print(s2)

Output

Hello CodeConfig
hello India


Explanation:

  • For s1, The original string s is sliced from index 1 to end of string and then concatenate “H” to create a new string s1.
  • For s2, we can created a new string s2 and have used replace() method to replace ‘CodeConfig’ with ‘India’.


Common String Methods

Python provides a various built-in functions/method to manipulate strings. Below are some of the most useful methods.

len(): The len() function/method returns the total number of characters in a string.


s = "CodeConfig"
print(len(s))

# output: 10

Output

10


upper() and lower(): upper() functions/method converts all characters to uppercase. lower() method converts all characters to lowercase.


s = "Hello World"

print(s.upper())   # output: HELLO WORLD

print(s.lower())   # output: hello world

Output

HELLO WORLD
hello world

strip() and replace(): strip() removes leading and trailing whitespace from the string and replace(old, new) replaces all occurrences of a specified substring with another.



s = "   ABC   "

# Removes spaces from both ends
print(s.strip())    

s = "Python is fun"

# Replaces 'fun' with 'awesome'
print(s.replace("fun", "awesome"))  

Output

ABC
Python is awesome

To learn more about string methods, please refer to Python String Methods.


Concatenating and Repeating Strings

We can concatenate strings using+ operator and repeat them using * operator.

Strings can be combined by using + operator.


s1 = "Hello"
s2 = "World"
s3 = s1 + " " + s2
print(s3)

Output

Hello World

We can repeat a string multiple times using * operator.


s = "Hello "
print(s * 3)

Output

Hello Hello Hello 


Formatting Strings

Python provides several ways to include variables inside strings.

Using f-strings

The simplest and most preferred way to format strings is by using f-strings.


name = "Alice"
age = 22
print(f"Name: {name}, Age: {age}")

Output

Name: Alice, Age: 22


Using format()

Another way to format strings is by using format() method.


s = "My name is {} and I am {} years old.".format("Alice", 22)
print(s) 

Output

My name is Alice and I am 22 years old.


Using in for String Membership Testing

The in keyword checks if a particular substring is present in a string.


s = "CodeConfig"
print("Code" in s)
print("ABC" in s)

Output

True
False


f-strings in Python


Python offers a powerful feature called f-strings (formatted string literals) to simplify string formatting and interpolation. f-strings is introduced in Python 3.6 it provides a concise and intuitive way to embed expressions and variables directly into strings. The idea behind f-strings is to make string interpolation simpler. 


How to use f-strings in Python


To create an f-string, prefix the string with the letter "f". The string itself can be formatted in much the same way that you would with str.format(). F-strings provide a concise and convenient way to embed Python expressions inside string literals for formatting. 

In the below example, we have used the f-string inside a print() functions/method to print a string. We use curly braces to use a variable value inside f-strings, so we define a variable ‘val’ with ‘Geeks’ and use this inside when seen in the code below ‘val’ with ‘Geeks’. Similarly, we use the ‘name’ and the variable inside a second print statement.

# Python3 program introducing f-string
val = 'Code-Config'
str='Coders'
print(f"{val} is a portal for {str}.")


name = 'Sham'
age = 32
print(f"Hello, my name is {name} and I'm {age} years old.")

Output

In this example, we have printed today’s date using the datetime module in Python with f-string. For that firstly, we import the datetime module after that we print the date using f-sting. Inside f-string ‘today’ assigned the current date and %B%d, and %Y represents the full monthday of month, and year respectively.

# Prints today's date with help
# of datetime library
import datetime

today = datetime.datetime.today()
print(f"{today:%B %d, %Y}")

Output

Note: F-strings are faster than the two most commonly have used string formatting mechanisms, which are % formatting and str.format(). 

To use any type of quotation marks with the f-string in Python we have to make sure that the quotation marks have used inside the expression are not the same when quotation marks have used with the f-string.

print(f"'CodeConfig'")

print(f"""code"for"fun""")

print(f'''code'for'fun''')

Output

We can also evaluate expressions with f-strings in Python. To do so we have to write the expression inside the curly braces in f-string and the evaluated result will be printed when shown in the below code’s output.

english = 80
maths = 60
hindi = 80

print(f"Mohan got total marks {english + Maths + Hindi} out of 300")

Output

Errors when using f-string in Python

In Python f-string, Backslash Cannot be have used in format string directly.

f"newline: {ord('\n')"

Output

However, we can put the backslash into a variable when a workaround over:

newline = ord('\n')

print(f"newline: {newline}")

String Slicing in Python


String Slicing in Python


String slicing in Python is a way to get specific parts of a string by using start, end, and step values. It's especially useful for text manipulation and data parsing.

Let's take a quick example of string slicing:



s = "Hello, Python!"

# Slice string from index 0 to index 5 (exclusive)
s2 = s[0:5]

print(s2)

Output

Hello

Explanation: In this example, we have used the slice s[0:5] to obtain the substring “Hello” from the original string.


Syntax of String Slicing in Python

substring = s[start : end : step]


Parameters:

  • s: The original string.
  • start (optional): Starting index (inclusive). Defaults to 0 if omitted.
  • end (optional): Stopping index (exclusive). Defaults to the end of the string if omitted.
  • step (optional): Interval between indices. A positive value slices from left to right, when a negative value slices from right to left. If omitted, it defaults to 1 (no skipping of characters).

Return Type

  • The result of a slicing operation is always a string (str type) that contains a subset of the characters from the original string.


String Slicing Examples

Let's review how to use string slicing in Python with the examples below.

Retrieve All Characters

To retrieve the entire string, use slicing without specifying any parameters.


s = "Hello, World!"

# Get the entire string
s2 = s[:]
s3 = s[::]

print(s2)
print(s3)

Output

Hello, World!
Hello, World!

Explanation: Using [:] or [::] without specifying start, end, or step returns the complete string.


Get All Characters Before or After a Specific Position

To get all the items from a specific position to the end of the string, we can specify the start index and leave the end blank.
And to get all the items before a specific index, we can specify the end index when leaving start blank.


s = "Hello, World!"

# Characters from index 7 to the end
print(s[7:])

# Characters from the start up to index 5 (exclusive)
print(s[:5])

Output

World!
Hello

Explanation: The slice s[7:] starts from index 7 and continues to the end of the string.


Extract Characters Between Two Positions

To extract characters between specific positions, provide both start and end indices.


s = "Hello, World!"

# Characters from index 1 to index 5 (excluding 5)
print(s[1:5]) 

Output

ello


Get Characters at Specific Intervals

To retrieve characters at regular intervals, use the step parameter.


s = "abcdefghi"

# Every second character
print(s[::2])

# Every third character from index 1 to 8 (exclusive)
print(s[1:8:3]) 

Output

acegi
beh

Explanation: The slice s[::2] takes every second character from the string.


Out-of-Bounds Slicing

In Python, String slicing allows out-of-bound indexing without raising errors. If indices exceed the string length, the slice returns just available characters without raising an error.

Example: The slice s[3:15] starts at index 3 and attempts to reach index 15, but if string ends at index 8 then it will return just the available elements.


Using Negative Indexing in Slicing

Negative indexing is useful for accessing elements from the end of the String. The last element has an index of -1, the second last element -2, and so on.


Extract Characters Using Negative Indices

Below example shows how to use negative numbers to access elements from the string starting from the end. Negative indexing makes it easy to get items without needing to know the exact length of the string.


s = "abcdefghijklmno"

# Characters from index -4 to the end
print(s[-4:])

# Characters from the start up to index -3 (excluding -3)
print(s[:-3])

# Characters from index -5 to -2 (excluding -2)
print(s[-5:-2])

# Get every 2nd elements from index -8 to -1 (excluding index -1)
print(s[-8:-1:2])

Output

lmno
abcdefghijkl
klm
hjln


Reverse a String Using Slicing

To reverse a string, use a negative step value of -1, which moves from the end of the string to the beginning.


s = "Python"

# Reverse the string
print(s[::-1])

Output

nohtyP

Explanation: The slice s[::-1] starts from the end and steps backward through the string, which effectively reversing it. This functions/method does not alter the original string.



No comments:

Post a Comment

Popular Posts