Wednesday, 1 March 2023

Operation on String in Python

Python provides many built-in operations for working with strings. Here are some of the most commonly used string operations in Python:

  1. String concatenation: To concatenate two or more strings, use the + operator.

Example:

python
s1 = "Hello" s2 = "world" s3 = s1 + s2 print(s3) # Output: "Helloworld"
  1. String indexing: You can access individual characters in a string using their index. In Python, string indices start from 0.

Example:

python
s = "Hello" print(s[0]) # Output: "H" print(s[1]) # Output: "e"
  1. String slicing: To extract a substring from a string, use slicing. Slicing allows you to specify a range of indices to extract.

Example:

python
s = "Hello world" print(s[0:5]) # Output: "Hello" print(s[6:]) # Output: "world"
  1. String formatting: You can insert values into a string using placeholders and the format method.

Example:

python
name = "Alice" age = 30 print("My name is {} and I am {} years old".format(name, age)) # Output: "My name is Alice and I am 30 years old"
  1. String methods: Python provides many built-in methods for working with strings, such as upper, lower, replace, split, and strip.

Example:

python
s = " Hello World " print(s.upper()) # Output: " HELLO WORLD " print(s.lower()) # Output: " hello world " print(s.replace("o", "x")) # Output: " Hellx Wxrld " print(s.split()) # Output: ["Hello", "World"] print(s.strip()) # Output: "Hello World"

These are just a few of the many string operations available in Python.

No comments:

Post a Comment

Program For String

 # This program demonstrates various string operations # Define a string variable my_string = "Hello, World!" # Print the string p...