ExampleGet your own Python Server Where in the text is the last occurrence of the string "casa"?: txt = "Mi casa, su casa."x = txt.rfind("casa")print(x) Try it Yourself » Definition and UsageThe rfind() method finds the last occurrence of the specified value....
ExampleGet your own Python Server Make the first letter in each word upper case: txt = "Welcome to my world"x = txt.title()print(x) Try it Yourself » Definition and UsageThe title() method returns a string where the first character in every word is upper case. Like a header, ...
There is no built-in function to reverse a String in Python. The fastest (and easiest?) way is to use a slice that steps backwards,-1. ExampleGet your own Python Server Reverse the string "Hello World": txt ="Hello World"[::-1] ...
❮ String Methods ExampleGet your own Python Server UTF-8 encode the string: txt ="My name is Ståle" x = txt.encode() print(x) Run example » Definition and Usage Theencode()method encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used...
Perform Operations in F-Strings You can perform Python operations inside the placeholders. You can do math operations: Example Perform a math operation in the placeholder, and return the result: txt = f"The price is {20 * 59} dollars" ...
ExampleGet your own Python Server Create a mapping table, and use it in thetranslate()method to replace any "S" characters with a "P" character: txt ="Hello Sam!" mytable =str.maketrans("S","P") print(txt.translate(mytable)) ...
❮ String Methods ExampleGet your own Python Server Replace the word "bananas": txt ="I like bananas" x = txt.replace("bananas","apples") print(x) Try it Yourself » Definition and Usage Thereplace()method replaces a specified phrase with another specified phrase. ...
ExampleGet your own Python Server Split a string into a list where each word is a list item: txt ="welcome to the jungle" x = txt.split() print(x) Try it Yourself » Definition and Usage Thesplit()method splits a string into a list. ...
ExampleGet your own Python Server Join all items in a tuple into a string, using a hash character as separator: myTuple = ("John","Peter","Vicky") x ="#".join(myTuple) print(x) Try it Yourself » Definition and Usage Thejoin()method takes all items in an iterable and joins the...
❮ String Methods ExampleGet your own Python Server Check if the string starts with "Hello": txt ="Hello, welcome to my world." x = txt.startswith("Hello") print(x) Try it Yourself » Definition and Usage Thestartswith()method returns True if the string starts with the specified va...