Python String
What are Python Strings?
- Python Strings are a sequences of characters used to represent text.
- Enclosed in single quotes (
'
) or double quotes ("
). - Immutable: Once created, their contents cannot be changed directly.
Python String Key Points
You should learn following important points, if you are new to Python String.
name = "Kuntal"greeting = 'Hello !!!'long_msg = """This is a multilinestring using triple quotes."""print(greeting)print(name)print(long_msg)
Output:
Hello !!!KuntalThis is a multilinestring using triple quotes.
first_char = name[0] # Access first characterlast_char = name[-1] # Access last characterprint(first_char)print(last_char)
Output:
Kl
3. Slicing Strings
substring = greeting[0:2] # Extract "He from Hello !!!"print(substring)
Output:
He
4. String Concatenation
full_message = greeting + " " + nameprint(full_message)
Output:
Hello !!! Kuntal
5. String Formatting
age = 40formatted_text = "My name is {} and I am {} years old.".format(name, age)print(formatted_text)
Output:
My name is Kuntal and I am 40 years old.
6. Common String Methods
print(name.upper()) # Convert to uppercaseprint(greeting.lower()) # Convert to lowercaseprint(long_msg.splitlines()) # Split into a list of lines
Output:
KUNTALhello !!!['This is a multiline', ' string using triple quotes.']
Additional Notes:
- Escape Sequences: Use backslashes (
\
) to represent special characters like newlines (\n
) and tabs (\t
). - Raw Strings: Prefix a string with
r
to ignore escape sequences:r'This string\nhas no newline'
Python is very good in String Processing. Strings can be enclosed in single quotes like 'PythonPracticals' or double quotes like "PythonPracticals".
>>> 'Python Practicals' # single quotes
'Python Practicals'
>>> "Python Practicals" # double quotes
'Python Practicals'
'Python Practicals'
>>> "Python Practicals" # double quotes
'Python Practicals'
Observe the following code:
>>> 'Python's Practicals'
SyntaxError: invalid syntax
SyntaxError: invalid syntax
String starts at first single quote (') and ends at second single ('); hence above statement will result in error. The correct way of printing single quote (') in string is as under:
# Use \' to print single quote
>>> 'Python\'s Practicals'
"Python's Practicals" >>> 'Python\'s Practicals'
#Another way to print ‘ is use double quote
>>> "Python's Practicals"
"Python's Practicals"
# Following two statements will produce same output
>>>'"Yes, you are correct"'
'"Yes, you are correct"'
>>> '\"Yes, you are correct\"'
'"Yes,you are correct"'
# To print string without start and end quote, use print( )
>>> print("Yes, you are correct")
Yes, you are correct
print() function
Python print() function produces a more readable output; it will omits the enclosing quotes while printing output as shown below:
#Use print() function to avoid quotes in output string
>>> print("PythonPracticals.Blogspot.Com")
PythonPracticals.Blogspot.Com
>>> print("PythonPracticals.Blogspot.Com")
PythonPracticals.Blogspot.Com
Multi line String output using Newline character
>>> print("Python\nPracticals\n.Blogspot\n.Com")
Python
Practicals
.Blogspot
.Com
# Note: \n is a newline character
Python
Practicals
.Blogspot
.Com
# Note: \n is a newline character
If you don’t want special characters (\n) to be interpreted as newline character, you can use raw strings by adding an r before the first quote as shown below:
# In following statement \n means newline
>>> print('C:\python\new’)
C:\pythonew
# r will remove the effect of \n
>>> print(r'C:\python\new')
C:\python\new
Multi line String output using Paragraph format
String can span across multiple lines. One way of doing this is use triple-quotes: """...""" or '''...'''. End of line ( \n ) is automatically included in the string:
>>> print("""Hello
Students
How are you?
""")
Hello
Students
How are you?
Students
How are you?
""")
Hello
Students
How are you?
Read more Python String Handouts
* * * * *
No comments:
Post a Comment