Python Strings
Strings are sequences of characters. They are immutable, meaning you cannot change a string once created.
1. Creating Strings:
Create strings using single (' '), double (" "), or triple quotes (''' ''' or """ """). Triple quotes are for multiline strings.
str1 = 'Hello' # Using single quotes
str2 = "AIT" # Using double quotes
str3 = '''This is a
multiline string''' # Using triple quotes
2. Accessing String Characters:
Access individual characters via indexing (0-based):
my_string = "Python"
print(my_string[0]) # P (first character at index 0)
print(my_string[-1]) # n (last character at index -1. Negative index accesses from right-to-left )
print(my_string[1:4]) # yth (slicing. Get characters from index 1 upto (not including) index 4.)
3. String Concatenation (+) :
Combine by joining or summing: +
greeting = "Hello"
name = "Shaista"
message = greeting + ", " + name + "!" # String concatenation
print(message) # Output: Hello, Shaista!
4. String Replication (*):
Replicates using a preceding numerical multiplicand indicating the number of replications: *
stars = "*" * 5 # * is string replication operator
print(stars) # *****
5. String Methods:
Python provides a large number of useful built-in functions available to operate over string types, some very common and useful examples:
text = " Hello, World! "
print(text.lower()) # hello, ait!
print(text.upper()) # HELLO, AIT!
print(text.strip()) # Hello, AIT! (leading/trailing white-spaces removed)
print(text.split(",")) # [' Hello', ' AIT! '] (splitting)
mystring= "aitacadamy"
print(len(mystring)) # prints 10 - shows length
6. String Formatting:
Several approaches are common. First by constructing combined values as in an f-string example: `message= f"{name}'s score: {score}"` . Using `message= "%s's score: %d " % (name, score)` if `score` expected integer, with f-string variant providing far more versatile means since allows expressions inside and more types
Next the .format() syntax : `msg = "Hello, {}. You are {}.".format(user,age)` for formatting in placeholder areas if intended, with a more advanced case, placeholder usage could align as well such as padding and more which would work better where number-style outputs relevant than prior simple example showing similar outcomes:
name = "Noorain"
age = 24
# Using f-strings (Python 3.6+): Most straightforward
message1 = f"Hello, {name}. You are {age}."
print(message1)
# Using .format(): More versatile
msg_format = "{}, {} and {}".format('John','Bill','Sean') # note arguments without specific ordering here
print(msg_format)
msg_format_ordered = "{1}, {0} and {2}".format('John','Bill','Sean') #now specific numeric indices given corresponding to argument in sequence
#formatted string literals (similar to preceding use-case with f-string)
message2 = f"{name} is {age} years old and has {marks:.0f} marks."