In Python, you can define a string variable by assigning a string value to a variable name. There are several ways to define a string in Python, including single quotes, double quotes, and triple quotes.
Here are some examples of defining string variables in Python:
1 2 3 4 5 6 7 8 9 10 11 12 |
Copy code<code># Define a string with single quotes name = 'John Smith' # Define a string with double quotes address = "123 Main Street" # Define a string with triple quotes bio = """John Smith is a software engineer who enjoys programming in Python.""" # Define a string with escape characters message = "Hello, \"John\"" |
In Python, strings are immutable, which means that you cannot change the individual characters in a string. However, you can create a new string that is a modified version of an existing string.
Here are some examples of modifying string variables in Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Copy code<code># Concatenate strings greeting = "Hello, " + name # Repeat a string repeated = name * 3 # Get a substring substring = name[0:5] # Replace a substring replaced = name.replace('John', 'Jane') # Convert a string to uppercase or lowercase uppercase = name.upper() lowercase = name.lower() |
It’s also important to note that Python has several built-in functions for working with strings, such as len
, strip
, split
, and join
. You can use these functions to manipulate and analyze strings in your code.