[Go to site: main page, start]

0% found this document useful (0 votes)
2 views6 pages

Python String Methods

The document provides a comprehensive overview of string manipulation in Python, covering creation, concatenation, repetition, indexing, slicing, and various string methods. It includes examples for string formatting using f-strings, format(), and the % operator, as well as escaping characters and using raw strings. The document serves as a practical guide for understanding and utilizing strings effectively in Python programming.

Uploaded by

Ajay Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views6 pages

Python String Methods

The document provides a comprehensive overview of string manipulation in Python, covering creation, concatenation, repetition, indexing, slicing, and various string methods. It includes examples for string formatting using f-strings, format(), and the % operator, as well as escaping characters and using raw strings. The document serves as a practical guide for understanding and utilizing strings effectively in Python programming.

Uploaded by

Ajay Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Basic String Creation


python
Copy code
single_quote_string = 'Hello, World!'
double_quote_string = "Hello, World!"
triple_quote_string = '''Hello,
World!'''

2. Concatenation

You can concatenate strings using the + operator.

python
Copy code
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2 # Output: "Hello World"

3. Repetition

You can repeat strings using the * operator.

python
Copy code
str1 = "Hello"
result = str1 * 3 # Output: "HelloHelloHello"

4. Indexing and Slicing

You can access individual characters and substrings using indexing and slicing.

python
Copy code
my_string = "Hello, World!"
first_char = my_string[0] # Output: 'H'
substring = my_string[0:5] # Output: 'Hello'

5. String Methods

Python provides many useful methods for strings.

 upper(): Converts all characters to uppercase.

python
Copy code
my_string = "Hello"
upper_string = my_string.upper() # Output: "HELLO"

 lower(): Converts all characters to lowercase.

python
Copy code
my_string = "Hello"
lower_string = my_string.lower() # Output: "hello"

 strip(): Removes leading and trailing whitespace.

python
Copy code
my_string = " Hello "
stripped_string = my_string.strip() # Output: "Hello"

 replace(): Replaces a substring with another substring.

python
Copy code
my_string = "Hello, World!"
new_string = my_string.replace("World", "Python") # Output: "Hello,
Python!"

 split(): Splits a string into a list of substrings.

python
Copy code
my_string = "Hello, World!"
words = my_string.split(", ") # Output: ['Hello', 'World!']

 join(): Joins a list of strings into a single string.

python
Copy code
words = ['Hello', 'World']
my_string = ', '.join(words) # Output: "Hello, World"

 find(): Finds the first occurrence of a substring.

python
Copy code
my_string = "Hello, World!"
index = my_string.find("World") # Output: 7

6. String Formatting

You can format strings using f-strings, format(), or % operators.

 Using f-strings (Python 3.6+):

python
Copy code
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old." #
Output: "My name is Alice and I am 30 years old."

 Using format():

python
Copy code
name = "Bob"
age = 25
formatted_string = "My name is {} and I am {} years
old.".format(name, age) # Output: "My name is Bob and I am 25 years
old."

 Using % operator:

python
Copy code
name = "Charlie"
age = 40
formatted_string = "My name is %s and I am %d years old." % (name,
age) # Output: "My name is Charlie and I am 40

With Examples:
1. Creating Strings

You can create strings using different types of quotes:

python
Copy code
single_quote_string = 'Hello, World!' # Single quotes
double_quote_string = "Hello, World!" # Double quotes
triple_quote_string = '''Hello,
World!''' # Triple quotes for multi-line strings

2. Concatenation

Combining strings using the + operator:

python
Copy code
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2 # Output: "Hello World"

3. Repetition

Repeating a string multiple times with the * operator:

python
Copy code
str1 = "Hello"
result = str1 * 3 # Output: "HelloHelloHello"

4. Indexing and Slicing

Accessing characters and substrings:


python
Copy code
my_string = "Hello, World!"
first_char = my_string[0] # Output: 'H' (first character)
substring = my_string[0:5] # Output: 'Hello' (characters from index 0 to
4)

 Negative Indexing: Start from the end of the string.

python
Copy code
last_char = my_string[-1] # Output: '!'

 Slicing with Step: Extract characters with a specific step.

python
Copy code
every_other_char = my_string[::2] # Output: 'Hlo ol!'

5. String Methods

Python provides a variety of methods to manipulate strings:

 upper(): Converts all characters to uppercase.

python
Copy code
my_string = "Hello"
upper_string = my_string.upper() # Output: "HELLO"

 lower(): Converts all characters to lowercase.

python
Copy code
my_string = "Hello"
lower_string = my_string.lower() # Output: "hello"

 strip(): Removes leading and trailing whitespace.

python
Copy code
my_string = " Hello "
stripped_string = my_string.strip() # Output: "Hello"

 replace(): Replaces occurrences of a substring with another substring.

python
Copy code
my_string = "Hello, World!"
new_string = my_string.replace("World", "Python") # Output: "Hello,
Python!"

 split(): Splits a string into a list based on a delimiter.

python
Copy code
my_string = "Hello, World!"
words = my_string.split(", ") # Output: ['Hello', 'World!']

 join(): Joins a list of strings into a single string.

python
Copy code
words = ['Hello', 'World']
my_string = ', '.join(words) # Output: "Hello, World"

 find(): Finds the index of the first occurrence of a substring. Returns -1 if not found.

python
Copy code
my_string = "Hello, World!"
index = my_string.find("World") # Output: 7

 count(): Counts the number of occurrences of a substring.

python
Copy code
my_string = "Hello, World! Hello!"
count = my_string.count("Hello") # Output: 2

 startswith(): Checks if the string starts with a specific substring.

python
Copy code
my_string = "Hello, World!"
starts_with_hello = my_string.startswith("Hello") # Output: True

 endswith(): Checks if the string ends with a specific substring.

python
Copy code
my_string = "Hello, World!"
ends_with_world = my_string.endswith("World!") # Output: True

6. String Formatting

Formatting strings to include variable values:

 Using f-strings (Python 3.6+):

python
Copy code
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old." #
Output: "My name is Alice and I am 30 years old."

 Using format():

python
Copy code
name = "Bob"
age = 25
formatted_string = "My name is {} and I am {} years
old.".format(name, age) # Output: "My name is Bob and I am 25 years
old."

 Using % operator:

python
Copy code
name = "Charlie"
age = 40
formatted_string = "My name is %s and I am %d years old." % (name,
age) # Output: "My name is Charlie and I am 40 years old."

7. Escaping Characters

Use backslashes to include special characters in strings:

python
Copy code
escaped_string = "She said, \"Hello!\"" # Output: She said, "Hello!"

8. Raw Strings

Raw strings treat backslashes as literal characters, useful for regular expressions:

python
Copy code
raw_string = r"C:\Users\Name" # Output: C:\Users\Name

You might also like