โค้ดป้อนอินพุทเป็นสตริง ภาษาไพทอน
- User
โค้ดป้อนอินพุทเป็นสตริง ภาษาไพทอน
- Assistant
การเขียนโค้ดเพื่อให้รับข้อมูลอินพุทเป็นสตริง (string) ในภาษาไพทอน (Python) สามารถทำได้โดยใช้ฟังก์ชัน
input()ดังตัวอย่างเบื้องต้นต่อไปนี้:# ขอให้ผู้ใช้ป้อนข้อมูลและเก็บไว้ในตัวแปรชื่อ input_string input_string = input("กรุณาป้อนข้อมูลของคุณ: ") # แสดงข้อมูลที่ผู้ใช้ป้อนมา print("ข้อมูลที่คุณป้อนคือ:", input_string)ในโค้ดนี้:
input()เป็นฟังก์ชันที่ใช้ในการรับข้อมูลจากผู้ใช้ผ่านทาง Command-Line Interface (CLI) หรือ Terminal การทำงานของมันจะหยุดชั่วคราวและรอให้ผู้ใช้ป้อนข้อมูลเข้าไป และเมื่อผู้ใช้กด Enter ข้อมูลที่ป้อนจะถูกส่งไปยังโปรแกรม"กรุณาป้อนข้อมูลของคุณ: "เป็นข้อความที่จะแสดงออกมาเพื่อแจ้งผู้ใช้ว่าควรป้อนข้อมูลประเภทใดinput_stringเป็นตัวแปรที่ใช้เก็บข้อมูลที่ผู้ใช้ป้อนเข้ามา โดยฟังก์ชันinput()จะคืนค่าเป็นสตริงprint()เป็นฟังก์ชันที่ใช้ในการแสดงผลข้อมูลออกมาทางหน้าจอ
ทุกครั้งที่คุณใช้ฟังก์ชัน
input()แล้วต้องการให้ข้อมูลที่ได้รับมีประเภทอื่นนอกจากสตริง เช่น จำนวนเต็มหรือจำนวนทศนิยม เราสามารถใช้ฟังก์ชันเพื่อเปลี่ยนประเภทข้อมูลได้ ดังตัวอย่างต่อไปนี้: - User
If the sentence is entered, let it split. If you find lowercase letters, print them out as case-sensitive. If you see capital letters, print them out with only capital letters. If the two letters are combined, type a combination of letters.# Create a function that takes a string as a parameter def split_letters(string): lower = [] # Empty list for lowercase letters upper = [] # Empty list for uppercase letters for letter in string: # Loop through each letter in the string if letter.islower(): # If the letter is lowercase lower.append(letter) # Add the letter to the lowercase list elif letter.isupper(): # If the letter is uppercase upper.append(letter) # Add the letter to the uppercase list return lower, upper # Return the lowercase and uppercase lists
Test the function with an example string
string = "HelloWorld" lower, upper = split_letters(string) # Call the function and store the result print("Lowercase letters:", lower) # Print the result print("Uppercase letters:", upper)
- Assistant