Skip to main content

Posts

Showing posts with the label string

f strings in Python

Learning Sections          show f-strings in Python f-strings, introduced in Python 3.6, provide a way to embed expressions inside string literals, using curly braces {} . They are prefixed with the letter f or F . Basic Usage f-strings are a concise and readable way to format strings. # Basic usage of f-strings name = "Alice" age = 30 greeting = f"Hello, my name is { name } and I am { age } years old." print ( greeting ) # Output: Hello, my name is Alice and I am 30 years old. Expressions in f-strings f-strings can include expressions, which are evaluated at runtime. # Expressions inside f-strings a = 5 b = 10 result = f"{ a + b }" print ( result ) # Output: 15 Calling Functions You can call functions within f-strings. # Calling functions inside f-strings def greet ( name ): retur...

String Methods in Python

Learning Sections      show Python String Methods 1. `upper()` and `lower()` s = "Hello, World!" print ( s . upper ()) # Output: HELLO, WORLD! print ( s . lower ()) # Output: hello, world! 2. `strip()`, `lstrip()`, and `rstrip()` s = " Hello, World! " print ( s . strip ()) # Output: "Hello, World!" print ( s . lstrip ()) # Output: "Hello, World! " print ( s . rstrip ()) # Output: " Hello, World!" 3. `split()` and `join()` s = "Hello, World!" words = s . split ( ", " ) print ( words ) # Output: ['Hello', 'World!'] print ( " - " . join ( words )) # Output: Hello - World! 4. `find()`, `rfind()`, `index()`, and `rindex()` s = "Hello, World!" print ( s . find ( "o" )) # Output: 4 print ( s . rfind ( "o" )) # Output: 8 print ( s . index ( "World" )) # Output: 7 5. `replace()` s = "Hello, Wor...

String Slicing and Operations on String in Python

  Learning Sections      show String slicing and operations in Python are fundamental concepts that allow for manipulation and access to substrings and various transformations. String Slicing String slicing allows you to extract parts of a string. The general form is: substring = string [start:stop:step] start: The starting index of the slice (inclusive). stop: The ending index of the slice (exclusive). step: The step size or interval between indices. 1. Basic Slicing: s = "Hello, World!" print ( s [ 0 : 5 ]) # Output: Hello 2. Strings with Negative Index print ( s [ -6 :]) # Output: World! print ( s [: -7 ]) # Output: Hello, Common String Operations 1. Concatenation str1 = "Hello" str2 = "World" result = str1 + " " + str2 print ( result ) # Output: Hello World 2. Repetitions str1 = "Ha" result = str1 * 3 print ( result ) # Output: HaHaHa 3. Membership print ( "ell" in ...