Python provides many built-in operations for working with strings. Here are some of the most commonly used string operations in Python:
- String concatenation:
To concatenate two or more strings, use the
+
operator.
Example:
pythons1 = "Hello"
s2 = "world"
s3 = s1 + s2
print(s3) # Output: "Helloworld"
- String indexing: You can access individual characters in a string using their index. In Python, string indices start from 0.
Example:
pythons = "Hello"
print(s[0]) # Output: "H"
print(s[1]) # Output: "e"
- String slicing: To extract a substring from a string, use slicing. Slicing allows you to specify a range of indices to extract.
Example:
pythons = "Hello world"
print(s[0:5]) # Output: "Hello"
print(s[6:]) # Output: "world"
- String formatting:
You can insert values into a string using placeholders and the
format
method.
Example:
pythonname = "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"
- String methods:
Python provides many built-in methods for working with strings, such as
upper
,lower
,replace
,split
, andstrip
.
Example:
pythons = " 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