String

Share: Facebook | Twitter | Whatsapp | Linkedin Visits: 508


Python String


#SCRIPTSKART

#
message = 'This is a string in Python'
print(message)

message = "This is also a string"
print(message)

#If a string contains a single quote, you should place it in double-quotes like this:
message = "It's a string"
print(message)

#when a string contains double quotes, you can use the single quotes:
message = '"Beautiful is better than ugly.". Said Tim Peters'
print(message)

#To escape the quotes, you use the backslash
message = 'It's also a valid string'
print(message)

#use raw strings by adding the letter r
message = r'C:pythonin'
print(message)

#multiple line string - To span a string multiple lines, you use triple-quotes “””…””” or ”’…”’
message = '''
Usage: mysql command
    -h hostname
    -d database name
    -u username
    -p password
'''
print(message)

#Using variables in Python strings with the f-strings

name = 'John'
message = f'Hi {name}'
print(message)

#Concatenating Python strings

message = 'Good ' 'Morning!'
print(message)

#Concatenating two string variable
greeting = 'Good '
time = 'Afternoon'

greeting = greeting + time + '!'
print(greeting)

#Accessing string elements

str = "Python String"
print(str[0]) # P
print(str[1]) # y

#If you use a negative index
str = "Python String"
print(str[-1])  # g
print(str[-2])  # n

#Getting the length of a string

str = "Python String"
str_len = len(str)
print(str_len)

#Slicing strings

str = "Python String"
print(str[0:2])

#modify string
str = "Python String"
new_str = 'J' + str[1:]
print(new_str)


#SCRIPTSKART