Computer Science Mathematics Practical-Python Strings

Python Strings

0 138

Assignment2: Python  Strings                            
Accessing value sin strings                 
● Updating strings
● String special operators
● Concatenation
● Repetition

 

Q1) write a python programming Accessing values in strings.

Ans:-

my_string = “Hello, World!”

 

# Accessing characters by index

first_char = my_string[0]    # First character

fifth_char = my_string[4]    # Fifth character

last_char = my_string[-1]    # Last character

 

Q2) write a python program updating in strings.

Ans:-

# Basic Python Program for String Updates

 

# Initial string

initial_string = “Hello, World!”

 

# Update 1: Appending text to the string

updated_string = initial_string + ” How are you?”

print(“After appending text:”, updated_string)

 

# Update 2: Replacing part of the string

# Replace ‘World’ with ‘Python’

replaced_string = updated_string.replace(“World”, “Python”)

print(“After replacing text:”, replaced_string)

 

# Update 3: Changing the entire string

new_string = “This is a completely new string.”

print(“After changing the entire string:”, new_string)

 

# Update 4: Converting string to uppercase

uppercase_string = new_string.upper()

print(“After converting to uppercase:”, uppercase_string)

 

# Update 5: Converting string to lowercase

lowercase_string = new_string.lower()

print(“After converting to lowercase:”, lowercase_string)

 

  

 

Q3) write a python program String special operators in strings.

 

Ans:-

# Define two example strings

string1 = “Hello”

string2 = “World”

 

# 1. Concatenation (+)

concatenated_string = string1 + ” ” + string2

print(“Concatenation: ” + concatenated_string)  # Output: Hello World

 

# 2. Repetition (*)

repeated_string = string1 * 3

print(“Repetition: ” + repeated_string)  # Output: HelloHelloHello

 

# 3. Membership (in)

if “Hell” in string1:

print(“‘Hell’ is in string1”)  # Output: ‘Hell’ is in string1

 

# 4. Not in (not in)

if “hell” not in string1:

print(“‘hell’ is not in string1”)  # Output: ‘hell’ is not in string1 (case-sensitive)

 

# 5. Slicing ([])

slice_string = string1[1:4]  # ‘ell’

print(“Sliced string: ” + slice_string)  # Output: ell

 

# 6. Range slicing ([start:end])

range_slice = string2[1:4]  # ‘orl’

print(“Range sliced string: ” + range_slice)  # Output: orl

 

# 7. String formatting (%)

formatted_string = “%s %s!” % (string1, string2)

print(“Formatted string: ” + formatted_string)  # Output: Hello World!

 

 

 

 

 

 

 

 

 

 

Leave A Reply

Your email address will not be published.