Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

python string

The document provides a comprehensive overview of strings in Python, covering their creation, basic operations, and methods for manipulation. It explains string immutability, indexing, slicing, joining, formatting, and various built-in methods for string handling. Additionally, it includes code examples to illustrate each concept clearly.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

python string

The document provides a comprehensive overview of strings in Python, covering their creation, basic operations, and methods for manipulation. It explains string immutability, indexing, slicing, joining, formatting, and various built-in methods for string handling. Additionally, it includes code examples to illustrate each concept clearly.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Strings in Python - A Detailed Explanation

1. Creating and Storing Strings

A string is a sequence of characters enclosed in single (' '), double (" "), or triple (''' ''' or """
""") quotes.

Examples:

python
Copy code
# Single and Double Quotes
str1 = 'Hello'
str2 = "Python"

# Triple Quotes (Used for multiline strings)


str3 = '''This is
a multiline
string.'''

Strings are immutable, meaning they cannot be changed once created.

2. Basic String Operations

Python provides several operations to work with strings.

i. Concatenation (+)

Used to join two strings.

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

ii. Repetition (*)

Repeats the string multiple times.

python
Copy code
print("Python " * 3) # Output: Python Python Python

iii. Membership Operators (in, not in)


Checks if a substring is present.

python
Copy code
text = "Hello Python"
print("Python" in text) # Output: True
print("Java" not in text) # Output: True

iv. String Length (len())

Returns the number of characters in a string.

python
Copy code
word = "Programming"
print(len(word)) # Output: 11

3. Accessing Characters in a String

We can access characters in a string using indexing.

i. Positive Indexing

Indexes start from 0 (left to right).

python
Copy code
text = "Python"
print(text[0]) # Output: P
print(text[3]) # Output: h

ii. Negative Indexing

Indexes start from -1 (right to left).

python
Copy code
text = "Python"
print(text[-1]) # Output: n
print(text[-3]) # Output: h

4. String Slicing and Joining

Slicing allows extracting parts of a string.

i. Basic Slicing (string[start:end:step])


python
Copy code
text = "Programming"

print(text[0:4]) # Output: Prog (0 to 3)


print(text[:6]) # Output: Progra (0 to 5)
print(text[3:]) # Output: gramming (3 to end)
print(text[::2]) # Output: Pormig (Every second character)
print(text[::-1]) # Output: gnimmargorP (Reversed string)

ii. Joining Strings (.join())

Used to join a list of strings into a single string.

python
Copy code
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence) # Output: Python is awesome

5. String Methods

Python provides many built-in methods to manipulate strings.

i. Changing Case

python
Copy code
text = "Hello World"

print(text.upper()) # Output: HELLO WORLD


print(text.lower()) # Output: hello world
print(text.title()) # Output: Hello World
print(text.capitalize()) # Output: Hello world
print(text.swapcase()) # Output: hELLO wORLD

ii. Checking String Properties

python
Copy code
print("Python123".isalnum()) # Output: True (Alphanumeric)
print("Python".isalpha()) # Output: True (Alphabetic)
print("123".isdigit()) # Output: True (Numbers only)
print("hello".islower()) # Output: True
print("HELLO".isupper()) # Output: True
print(" ".isspace()) # Output: True (Whitespace only)

iii. Searching and Replacing

python
Copy code
text = "I love Python"
print(text.find("Python")) # Output: 7 (Index of first occurrence)
print(text.replace("love", "like")) # Output: I like Python

iv. Splitting Strings

python
Copy code
sentence = "Python is easy to learn"
words = sentence.split() # Splits by space
print(words) # Output: ['Python', 'is', 'easy', 'to', 'learn']

csv_data = "Apple, Mango, Banana"


fruits = csv_data.split(", ") # Splits by comma
print(fruits) # Output: ['Apple', 'Mango', 'Banana']

6. Formatting Strings

Python provides multiple ways to format strings dynamically.

i. Using format()

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

ii. Using f-strings (Python 3.6+)

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

iii. Using % Formatting (Old method)

python
Copy code
name = "Bob"
marks = 90
print("Student: %s, Marks: %d" % (name, marks))
# Output: Student: Bob, Marks: 90

You might also like