Strings and Character Data

Case Conversion

Converts the target string to “title case.”

'the sun also rises'.title()

# 'The Sun Also Rises'
'FOO Bar 123 baz qUX'.swapcase()  # สลับตัวเล็กตัวใหญ่

# 'foo bAR 123 BAZ Qux'

'FOO Bar 123 baz qUX'.upper() # ตัวพิมพ์ใหญ่ทั้งหมด

# 'FOO BAR 123 BAZ QUX'

'FOO Bar 123 baz qUX'.lower()  # ตัวพิมพ์เล็กทั้งหมด

# 'foo bar 123 baz qux'

s = 'foO BaR BAZ quX'  # ตัวอักษรตัวแรกเป็นตัวพิมพ์ใหญ่
s.capitalize()

#  'Foo bar baz qux'

str.split('a,b,c', ',')

# abc

'this is my string'.split()

#['this', 'is', 'my', 'string']

>>> s = ' this   is  my string '
>>> s.split()

#['this', 'is', 'my', 'string']

>>> s.split(' ')
#['', 'this', '', '', 'is', '', 'my', 'string', '']

# Limiting Splits With Maxsplit

>>> s = "this is my string"
>>> s.split(maxsplit=1)

#['this', 'is my string']

Check Special Character

# import required package 
import re 
  
# Function checks if the string 
# contains any special character 
def check_special_char(string): 
  
    # Make own character set and pass  
    # this as argument in compile method 
    regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]') 
      
    # Pass the string in search  
    # method of regex object.     
    if(regex.search(string) == None): 
        print("String is accepted") 
          
    else: 
        print("String is not accepted.") 

# Enter the string 
string = "Geeks$For$Geeks"
      
# calling run function  
check_special_char(string)

 # String is not accepted. 

String Constant

import string

string.digits  # digit

# 0123456789

string.ascii_lowercase

# 'abcdefghijklmnopqrstuvwxyz'

string.ascii_uppercase

# 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

string.ascii_letters

# 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

string.hexdigits

# 0123456789abcdefABCDEF

string.printable

# '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR
# STUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

Last updated